-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathcustom-api-discovery.js
More file actions
289 lines (256 loc) · 10.5 KB
/
custom-api-discovery.js
File metadata and controls
289 lines (256 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
* Copyright (c) 2025, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {loadConfig, getOAuthToken, callCustomApiDxEndpoint, logMCPMessage} from '../utils/utils.js'
import {
parseWebDAVDirectories,
parseWebDAVResponse,
makeWebDAVPropfindRequest,
validateWebDAVResponse,
makeWebDAVGetRequest
} from '../utils/webdav-utils.js'
/**
* Creates a structured JSON response object
*/
function toJsonResponse(data, activeCodeVersion = null) {
const response = {
metadata: {
activeCodeVersion: activeCodeVersion,
timestamp: new Date().toISOString(),
totalApis: data?.length || 0
},
customApis: data || []
}
return {
content: [
{
type: 'text',
text: JSON.stringify(response, null, 2)
}
]
}
}
/**
* Creates an error response object
*/
function toErrorResponse(error, customApis = []) {
const errorResponse = {
error: error.message,
customApis: customApis
}
return {
content: [
{
type: 'text',
text: JSON.stringify(errorResponse, null, 2)
}
]
}
}
/**
* Fetches and validates OAuth token
*/
async function fetchAndValidateOAuthToken(clientId, clientSecret, oauthScope) {
const response = await getOAuthToken(clientId, clientSecret, oauthScope)
const responseData = await response.json()
if (!response.ok) {
const errorMessage = `Invalid OAuth response. Status: ${response.status}. Error: ${response.statusText}. Description: ${responseData.error_description}`
throw new Error(errorMessage)
}
return responseData
}
/**
* Fetches and validates Custom API DX response
*/
async function fetchAndValidateCustomApiDxResponse(accessToken, customApiHost, organizationId) {
const response = await callCustomApiDxEndpoint(accessToken, customApiHost, organizationId)
const responseData = await response.json()
if (!response.ok) {
const errorMessage = `Invalid Custom API DX response. Status: ${response.status}. Error: ${response.statusText}. Description: ${responseData.detail}`
throw new Error(errorMessage)
}
return responseData
}
/**
* Fetches and validates configuration from dw.json or environment variables
*/
function fetchAndValidateConfigs() {
// Load configuration from dw.json or environment variables
const config = loadConfig()
const {clientId, clientSecret, organizationId, instanceId, shortCode, hostname} = config
// Validate configuration fields
const nullConfigFields = Object.entries(config)
.filter(([, value]) => value === null || value === undefined)
.map(([key]) => key)
if (nullConfigFields.length > 0) {
throw new Error(`Required configuration fields are null: ${nullConfigFields.join(', ')}`)
}
return {clientId, clientSecret, organizationId, instanceId, shortCode, hostname}
}
/**
* Recursively searches for files related to an endpoint within a cartridge
*/
async function searchForEndpointFiles(
hostname,
accessToken,
activeCodeVersion,
cartridgeName,
apiName
) {
const searchResults = []
const baseUrl = `${hostname}/on/demandware.servlet/webdav/Sites/Cartridges/${activeCodeVersion}/${cartridgeName}/`
try {
// First, get the root cartridge directory structure
const response = await makeWebDAVPropfindRequest(baseUrl, accessToken)
validateWebDAVResponse(response)
// Parse the XML response to find directories to search for the API name folder
const responseText = await response.text()
const directories = parseWebDAVDirectories(responseText)
// Search recursively in each subdirectory for the API name folder
for (const dir of directories) {
const foundInDir = await searchRecursivelyForApiName(
baseUrl,
dir,
accessToken,
apiName,
'',
0
)
if (foundInDir.searchResults && foundInDir.searchResults.length > 0) {
searchResults.push(...foundInDir.searchResults)
}
}
} catch (error) {
logMCPMessage(`Error searching for endpoint files: ${error}`)
}
return {searchResults}
}
/**
* Recursively search for API name folder in a directory and its subdirectories
*/
async function searchRecursivelyForApiName(
baseUrl,
currentDir,
accessToken,
apiName,
currentPath,
depth = 0
) {
const searchResults = []
// Normalize path building to avoid double slashes
const dirUrl = `${baseUrl.replace(/\/$/, '')}/${currentDir.replace(/^\//, '')}/`
const fullPath = currentPath ? `${currentPath}/${currentDir}` : currentDir
try {
const dirResponse = await makeWebDAVPropfindRequest(dirUrl, accessToken)
validateWebDAVResponse(dirResponse)
const dirText = await dirResponse.text()
const items = parseWebDAVResponse(dirText)
// Check if the API name folder is in this directory
const apiNameFolder = items.find((item) => item.toLowerCase() === apiName.toLowerCase())
// Only try to fetch schema if folder exists
if (apiNameFolder) {
let schemaContent = null
const schemaUrl = `${dirUrl}${apiNameFolder}/schema.yaml`
const schemaResponse = await makeWebDAVGetRequest(schemaUrl, accessToken)
validateWebDAVResponse(schemaResponse)
schemaContent = await schemaResponse.text()
searchResults.push({
directory: fullPath,
apiNameFolder: apiNameFolder,
fullPath: `${fullPath}/${apiNameFolder}`,
schemaContent: schemaContent
})
}
// Get subdirectories using proper directory detection
const subdirs = parseWebDAVDirectories(dirText)
for (const subdir of subdirs) {
const subResults = await searchRecursivelyForApiName(
baseUrl,
`${currentDir}/${subdir}`,
accessToken,
apiName,
fullPath,
depth + 1
)
searchResults.push(...subResults.searchResults)
}
} catch (error) {
logMCPMessage(`Error searching recursively for API name: ${error}`)
}
return {searchResults}
}
export default {
name: 'scapi_custom_api_discovery',
description:
'Discovers and retrieves information about custom APIs deployed in Salesforce Commerce Cloud instances. Use this tool when you need to: find available custom APIs, get API schemas/documentation, understand API endpoints and methods, or analyze custom API implementations. This tool searches through SFCC cartridges, retrieves OAuth tokens, and fetches comprehensive API metadata including endpoints, HTTP methods, security schemes, and OpenAPI schemas.',
inputSchema: {},
fn: async () => {
let dxEndpointResponse = null
let activeCodeVersion = null
const {clientId, clientSecret, organizationId, instanceId, shortCode, hostname} =
fetchAndValidateConfigs()
const customApiHost = `${shortCode}.api.commercecloud.salesforce.com`
const oauthScope = `SALESFORCE_COMMERCE_API:${instanceId} sfcc.custom-apis`
try {
// Get OAuth token
const tokenData = await fetchAndValidateOAuthToken(clientId, clientSecret, oauthScope)
// Call custom API DX endpoint and retrieve custom APIs on the instance
dxEndpointResponse = await fetchAndValidateCustomApiDxResponse(
tokenData.access_token,
customApiHost,
organizationId
)
activeCodeVersion = dxEndpointResponse.activeCodeVersion
if (!dxEndpointResponse.data) {
return toJsonResponse([], activeCodeVersion)
}
// Process each custom API and attempt to get the schema content from WebDAV
// If the schema content is not found, still create the entry with content from DX response
const processedEntries = []
for (const entry of dxEndpointResponse.data) {
if (entry.cartridgeName) {
const endpointPath = entry.endpointPath.startsWith('/')
? entry.endpointPath.substring(1)
: entry.endpointPath
let customApiBaseUrl = null
let schemaContent = null
try {
// Construct the custom API base URL
customApiBaseUrl = `https://${shortCode}.api.commercecloud.salesforce.com/custom/${entry.apiName}/${entry.apiVersion}/organizations/${organizationId}/${endpointPath}`
const webdavResponse = await searchForEndpointFiles(
hostname,
tokenData.access_token,
activeCodeVersion,
entry.cartridgeName,
entry.apiName
)
// Extract schema content from the first successful result
schemaContent = webdavResponse?.searchResults?.[0]?.schemaContent || null
} catch (webdavError) {
logMCPMessage(`Error fetching custom API schema: ${webdavError}`)
}
// Create the processed entry with necessary fields
const processedEntry = {
apiName: entry.apiName,
apiVersion: entry.apiVersion,
cartridgeName: entry.cartridgeName,
endpointPath: endpointPath,
httpMethod: entry.httpMethod,
status: entry.status,
securityScheme: entry.securityScheme,
siteId: entry.siteId,
baseUrl: customApiBaseUrl,
schema: schemaContent
}
processedEntries.push(processedEntry)
}
}
return toJsonResponse(processedEntries, activeCodeVersion)
} catch (error) {
return toErrorResponse(error, dxEndpointResponse?.data || [])
}
}
}