-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathmcp-client.js
More file actions
290 lines (255 loc) · 8.88 KB
/
mcp-client.js
File metadata and controls
290 lines (255 loc) · 8.88 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
290
import { generateAuthUrl } from "./auth.server";
import { getCustomerToken } from "./db.server";
/**
* Client for interacting with Model Context Protocol (MCP) API endpoints.
* Manages connections to both customer and storefront MCP endpoints, and handles tool invocation.
*/
class MCPClient {
/**
* Creates a new MCPClient instance.
*
* @param {string} hostUrl - The base URL for the shop
* @param {string} conversationId - ID for the current conversation
* @param {string} shopId - ID of the Shopify shop
*/
constructor(hostUrl, conversationId, shopId, customerMcpEndpoint) {
this.tools = [];
this.customerTools = [];
this.storefrontTools = [];
// TODO: Make this dynamic, for that first we need to allow access of mcp tools on password proteted demo stores.
this.storefrontMcpEndpoint = `${hostUrl}/api/mcp`;
const accountHostUrl = hostUrl.replace(/(\.myshopify\.com)$/, '.account$1');
this.customerMcpEndpoint = customerMcpEndpoint || `${accountHostUrl}/customer/api/mcp`;
this.customerAccessToken = "";
this.conversationId = conversationId;
this.shopId = shopId;
}
/**
* Connects to the customer MCP server and retrieves available tools.
* Attempts to use an existing token or will proceed without authentication.
*
* @returns {Promise<Array>} Array of available customer tools
* @throws {Error} If connection to MCP server fails
*/
async connectToCustomerServer() {
try {
console.log(`Connecting to MCP server at ${this.customerMcpEndpoint}`);
if (this.conversationId) {
const dbToken = await getCustomerToken(this.conversationId);
if (dbToken && dbToken.accessToken) {
this.customerAccessToken = dbToken.accessToken;
} else {
console.log("No token in database for conversation:", this.conversationId);
}
}
// If we still don't have a token, we'll connect without one
// and tools that require auth will prompt for it later
const headers = {
"Content-Type": "application/json",
"Authorization": this.customerAccessToken || ""
};
const response = await this._makeJsonRpcRequest(
this.customerMcpEndpoint,
"tools/list",
{},
headers
);
// Extract tools from the JSON-RPC response format
const toolsData = response.result && response.result.tools ? response.result.tools : [];
const customerTools = this._formatToolsData(toolsData);
this.customerTools = customerTools;
this.tools = [...this.tools, ...customerTools];
return customerTools;
} catch (e) {
console.error("Failed to connect to MCP server: ", e);
throw e;
}
}
/**
* Connects to the storefront MCP server and retrieves available tools.
*
* @returns {Promise<Array>} Array of available storefront tools
* @throws {Error} If connection to MCP server fails
*/
async connectToStorefrontServer() {
try {
console.log(`Connecting to MCP server at ${this.storefrontMcpEndpoint}`);
const headers = {
"Content-Type": "application/json"
};
const response = await this._makeJsonRpcRequest(
this.storefrontMcpEndpoint,
"tools/list",
{},
headers
);
// Extract tools from the JSON-RPC response format
const toolsData = response.result && response.result.tools ? response.result.tools : [];
const storefrontTools = this._formatToolsData(toolsData);
this.storefrontTools = storefrontTools;
this.tools = [...this.tools, ...storefrontTools];
return storefrontTools;
} catch (e) {
console.error("Failed to connect to MCP server: ", e);
throw e;
}
}
/**
* Dispatches a tool call to the appropriate MCP server based on the tool name.
*
* @param {string} toolName - Name of the tool to call
* @param {Object} toolArgs - Arguments to pass to the tool
* @returns {Promise<Object>} Result from the tool call
* @throws {Error} If tool is not found or call fails
*/
async callTool(toolName, toolArgs) {
if (this.customerTools.some(tool => tool.name === toolName)) {
return this.callCustomerTool(toolName, toolArgs);
} else if (this.storefrontTools.some(tool => tool.name === toolName)) {
return this.callStorefrontTool(toolName, toolArgs);
} else {
throw new Error(`Tool ${toolName} not found`);
}
}
/**
* Calls a tool on the storefront MCP server.
*
* @param {string} toolName - Name of the storefront tool to call
* @param {Object} toolArgs - Arguments to pass to the tool
* @returns {Promise<Object>} Result from the tool call
* @throws {Error} If the tool call fails
*/
async callStorefrontTool(toolName, toolArgs) {
try {
console.log("Calling storefront tool", toolName, toolArgs);
const headers = {
"Content-Type": "application/json"
};
const response = await this._makeJsonRpcRequest(
this.storefrontMcpEndpoint,
"tools/call",
{
name: toolName,
arguments: toolArgs,
},
headers
);
return response.result || response;
} catch (error) {
console.error(`Error calling tool ${toolName}:`, error);
throw error;
}
}
/**
* Calls a tool on the customer MCP server.
* Handles authentication if needed.
*
* @param {string} toolName - Name of the customer tool to call
* @param {Object} toolArgs - Arguments to pass to the tool
* @returns {Promise<Object>} Result from the tool call or auth error
* @throws {Error} If the tool call fails
*/
async callCustomerTool(toolName, toolArgs) {
try {
console.log("Calling customer tool", toolName, toolArgs);
// First try to get a token from the database for this conversation
let accessToken = this.customerAccessToken;
if (!accessToken || accessToken === "") {
const dbToken = await getCustomerToken(this.conversationId);
if (dbToken && dbToken.accessToken) {
accessToken = dbToken.accessToken;
this.customerAccessToken = accessToken; // Store it for later use
} else {
console.log("No token in database for conversation:", this.conversationId);
}
}
const headers = {
"Content-Type": "application/json",
"Authorization": accessToken
};
try {
const response = await this._makeJsonRpcRequest(
this.customerMcpEndpoint,
"tools/call",
{
name: toolName,
arguments: toolArgs,
},
headers
);
return response.result || response;
} catch (error) {
// Handle 401 specifically to trigger authentication
if (error.status === 401) {
console.log("Unauthorized, generating authorization URL for customer");
// Generate auth URL
const authResponse = await generateAuthUrl(this.conversationId, this.shopId);
// Instead of retrying, return the auth URL for the front-end
return {
error: {
type: "auth_required",
data: `You need to authorize the app to access your customer data. [Click here to authorize](${authResponse.url})`
}
};
}
// Re-throw other errors
throw error;
}
} catch (error) {
console.error(`Error calling tool ${toolName}:`, error);
return {
error: {
type: "internal_error",
data: `Error calling tool ${toolName}: ${error.message}`
}
};
}
}
/**
* Makes a JSON-RPC request to the specified endpoint.
*
* @private
* @param {string} endpoint - The endpoint URL
* @param {string} method - The JSON-RPC method to call
* @param {Object} params - Parameters for the method
* @param {Object} headers - HTTP headers for the request
* @returns {Promise<Object>} Parsed JSON response
* @throws {Error} If the request fails
*/
async _makeJsonRpcRequest(endpoint, method, params, headers) {
const response = await fetch(endpoint, {
method: "POST",
headers: headers,
body: JSON.stringify({
jsonrpc: "2.0",
method: method,
id: 1,
params: params
}),
});
if (!response.ok) {
const error = await response.text();
const errorObj = new Error(`Request failed: ${response.status} ${error}`);
errorObj.status = response.status;
throw errorObj;
}
return await response.json();
}
/**
* Formats raw tool data into a consistent format.
*
* @private
* @param {Array} toolsData - Raw tools data from the API
* @returns {Array} Formatted tools data
*/
_formatToolsData(toolsData) {
return toolsData.map((tool) => {
return {
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema || tool.input_schema,
};
});
}
}
export default MCPClient;