-
Notifications
You must be signed in to change notification settings - Fork 4
feat: add MCP tools and complete product feed spec #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
e0281f6
e9c53f9
4d3b06b
e1347e2
e284a55
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| /** | ||
| * Configuration for creating MCP handlers | ||
| */ | ||
| export interface HandlerConfig { | ||
| /** | ||
| * Base URL of your store's API (e.g., 'https://mystore.com') | ||
| */ | ||
| baseUrl: string; | ||
|
|
||
| /** | ||
| * Optional headers to include in all requests (e.g., auth tokens) | ||
| */ | ||
| headers?: Record<string, string>; | ||
|
|
||
| /** | ||
| * Optional fetch implementation (useful for testing or custom logic) | ||
| */ | ||
| fetch?: typeof fetch; | ||
| } | ||
|
|
||
| /** | ||
| * Create handlers that call your acp-handler API endpoints | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const handlers = createHandlers({ | ||
| * baseUrl: 'https://mystore.com', | ||
| * headers: { 'Authorization': 'Bearer token' } | ||
| * }); | ||
| * | ||
| * server.registerTool( | ||
| * 'search_products', | ||
| * tools.searchProducts, | ||
| * handlers.searchProducts | ||
| * ); | ||
| * ``` | ||
| */ | ||
| export function createHandlers(config: HandlerConfig) { | ||
| const { baseUrl, headers = {}, fetch: customFetch = fetch } = config; | ||
|
|
||
| const request = async ( | ||
| path: string, | ||
| options: RequestInit = {}, | ||
| ): Promise<unknown> => { | ||
| const url = `${baseUrl}${path}`; | ||
| const response = await customFetch(url, { | ||
| ...options, | ||
| headers: { | ||
| "Content-Type": "application/json", | ||
| ...headers, | ||
| ...options.headers, | ||
| }, | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| const error = await response.json().catch(() => ({ | ||
| message: response.statusText, | ||
| })); | ||
| throw new Error( | ||
| `API request failed: ${error.message || response.statusText}`, | ||
| ); | ||
| } | ||
|
|
||
| return response.json(); | ||
| }; | ||
|
|
||
| return { | ||
| /** | ||
| * Search for products in the catalog | ||
| */ | ||
| searchProducts: async (input: { | ||
| query: string; | ||
| category?: string; | ||
| limit?: number; | ||
| }): Promise<unknown> => { | ||
| const params = new URLSearchParams({ | ||
| q: input.query, | ||
| }); | ||
|
|
||
| if (input.category) { | ||
| params.set("category", input.category); | ||
| } | ||
|
|
||
| if (input.limit) { | ||
| params.set("limit", String(input.limit)); | ||
| } | ||
|
|
||
| return request(`/api/products/search?${params}`); | ||
| }, | ||
|
|
||
| /** | ||
| * Get detailed information about a specific product | ||
| */ | ||
| getProduct: async (input: { product_id: string }): Promise<unknown> => { | ||
| return request(`/api/products/${input.product_id}`); | ||
| }, | ||
|
|
||
| /** | ||
| * Create a new checkout session | ||
| */ | ||
| createCheckout: async (input: any): Promise<unknown> => { | ||
| return request("/api/checkout", { | ||
| method: "POST", | ||
| body: JSON.stringify(input), | ||
| }); | ||
| }, | ||
|
|
||
| /** | ||
| * Update an existing checkout session | ||
| */ | ||
| updateCheckout: async (input: any): Promise<unknown> => { | ||
| const { session_id, ...body } = input; | ||
| return request(`/api/checkout/${session_id}`, { | ||
| method: "PATCH", | ||
| body: JSON.stringify(body), | ||
| }); | ||
|
Comment on lines
+113
to
+128
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The MCP handlers send data directly to ACP endpoints without transforming the schema, causing validation failures. The MCP tool schemas use different field names than the ACP API expects (e.g., View Details📝 Patch Detailsdiff --git a/packages/sdk/src/mcp/handlers.ts b/packages/sdk/src/mcp/handlers.ts
index 7e77098..0f67057 100644
--- a/packages/sdk/src/mcp/handlers.ts
+++ b/packages/sdk/src/mcp/handlers.ts
@@ -40,6 +40,88 @@ export interface HandlerConfig {
getCheckoutUrl?: (sessionId: string) => string;
}
+/**
+ * Transform MCP data to ACP schema
+ * MCP has customer: { email, name } and fulfillment: { address }
+ * ACP has customer: { shipping_address: Address }
+ * We need to merge the customer info with the fulfillment address
+ */
+function transformToACP(input: {
+ customer?: { email?: string; name?: string };
+ fulfillment?: {
+ selected_option_id?: string;
+ address?: {
+ line1: string;
+ line2?: string;
+ city: string;
+ state?: string;
+ postal_code: string;
+ country: string;
+ };
+ };
+}): {
+ customer?: {
+ shipping_address?: {
+ name?: string;
+ email?: string;
+ line1: string;
+ line2?: string;
+ city: string;
+ region?: string;
+ postal_code: string;
+ country: string;
+ };
+ };
+ fulfillment?: { selected_id?: string };
+} {
+ const result: any = {};
+
+ // Build shipping address from customer info + fulfillment address
+ if (input.fulfillment?.address) {
+ result.customer = {
+ shipping_address: {
+ line1: input.fulfillment.address.line1,
+ ...(input.fulfillment.address.line2 && {
+ line2: input.fulfillment.address.line2,
+ }),
+ city: input.fulfillment.address.city,
+ ...(input.fulfillment.address.state && {
+ region: input.fulfillment.address.state,
+ }),
+ postal_code: input.fulfillment.address.postal_code,
+ country: input.fulfillment.address.country,
+ ...(input.customer?.name && { name: input.customer.name }),
+ ...(input.customer?.email && { email: input.customer.email }),
+ },
+ };
+ }
+
+ // Transform fulfillment selected_option_id to selected_id
+ if (input.fulfillment?.selected_option_id) {
+ result.fulfillment = {
+ selected_id: input.fulfillment.selected_option_id,
+ };
+ }
+
+ return result;
+}
+
+/**
+ * Transform MCP payment data to ACP schema
+ * MCP: { method, token } → ACP: { method, delegated_token }
+ */
+function transformPayment(mcpPayment: {
+ method?: string;
+ token?: string;
+}): { method?: string; delegated_token?: string } | undefined {
+ if (!mcpPayment) return undefined;
+
+ return {
+ ...(mcpPayment.method && { method: mcpPayment.method }),
+ ...(mcpPayment.token && { delegated_token: mcpPayment.token }),
+ };
+}
+
/**
* Create handlers that call your acp-handler API endpoints
*
@@ -121,9 +203,16 @@ export function createHandlers(config: HandlerConfig) {
* Create a new checkout session
*/
createCheckout: async (input: any): Promise<unknown> => {
+ // Transform MCP schema to ACP schema
+ const transformed = transformToACP(input);
+ const acpBody: any = {
+ items: input.items,
+ ...transformed,
+ };
+
return request("/api/checkout", {
method: "POST",
- body: JSON.stringify(input),
+ body: JSON.stringify(acpBody),
});
},
@@ -131,10 +220,18 @@ export function createHandlers(config: HandlerConfig) {
* Update an existing checkout session
*/
updateCheckout: async (input: any): Promise<unknown> => {
- const { session_id, ...body } = input;
+ const { session_id, ...mcpBody } = input;
+
+ // Transform MCP schema to ACP schema
+ const transformed = transformToACP(mcpBody);
+ const acpBody: any = {
+ ...(mcpBody.items && { items: mcpBody.items }),
+ ...transformed,
+ };
+
return request(`/api/checkout/${session_id}`, {
method: "POST",
- body: JSON.stringify(body),
+ body: JSON.stringify(acpBody),
});
},
@@ -173,9 +270,14 @@ export function createHandlers(config: HandlerConfig) {
// ACP context: payment token provided
// Process payment through ACP complete endpoint
+ // Transform MCP schema to ACP schema
+ const acpBody: any = {
+ ...(payment && { payment: transformPayment(payment) }),
+ };
+
return request(`/api/checkout/${session_id}/complete`, {
method: "POST",
- body: JSON.stringify({ customer, payment }),
+ body: JSON.stringify(acpBody),
});
},
AnalysisSchema mismatch between MCP handlers and ACP API prevents checkout completionWhat fails: MCP handlers in How to reproduce:
{
customer: { email: "test@example.com", name: "John Doe" },
fulfillment: {
selected_option_id: "express",
address: { line1: "123 Main", city: "Seattle", postal_code: "98101", country: "US" }
}
}
Result: ACP handler receives Expected: MCP handlers should transform data to match ACP schema before sending requests, mapping Fix: Added transformation functions |
||
| }, | ||
|
|
||
| /** | ||
| * Complete a checkout session and process payment | ||
| */ | ||
| completeCheckout: async (input: any): Promise<unknown> => { | ||
| const { session_id, ...body } = input; | ||
| return request(`/api/checkout/${session_id}/complete`, { | ||
| method: "POST", | ||
| body: JSON.stringify(body), | ||
| }); | ||
| }, | ||
|
|
||
| /** | ||
| * Cancel a checkout session | ||
| */ | ||
| cancelCheckout: async (input: { session_id: string }): Promise<unknown> => { | ||
| const { session_id } = input; | ||
| return request(`/api/checkout/${session_id}/cancel`, { | ||
| method: "POST", | ||
| }); | ||
| }, | ||
|
|
||
| /** | ||
| * Get the current state of a checkout session | ||
| */ | ||
| getCheckout: async (input: { session_id: string }): Promise<unknown> => { | ||
| return request(`/api/checkout/${input.session_id}`); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Type for the handlers object returned by createHandlers | ||
| */ | ||
| export type Handlers = ReturnType<typeof createHandlers>; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| /** | ||
| * MCP (Model Context Protocol) tools for acp-handler | ||
| * | ||
| * This module provides tool definitions and handlers to expose your acp-handler | ||
| * checkout API as MCP tools for ChatGPT Apps. This allows merchants to sell | ||
| * products through ChatGPT without waiting for ACP approval. | ||
| * | ||
| * @example Basic usage | ||
| * ```typescript | ||
| * import { McpServer } from 'mcp-handler'; | ||
| * import { tools, createHandlers } from 'acp-handler/mcp'; | ||
| * | ||
| * const server = new McpServer({ name: 'my-store' }); | ||
| * const handlers = createHandlers({ baseUrl: 'https://mystore.com' }); | ||
| * | ||
| * // Register all tools | ||
| * server.registerTool('search_products', tools.searchProducts, handlers.searchProducts); | ||
| * server.registerTool('create_checkout', tools.createCheckout, handlers.createCheckout); | ||
| * server.registerTool('complete_checkout', tools.completeCheckout, handlers.completeCheckout); | ||
| * | ||
| * server.start(); | ||
| * ``` | ||
| * | ||
| * @example With customization | ||
| * ```typescript | ||
| * import { McpServer } from 'mcp-handler'; | ||
| * import { tools, createHandlers } from 'acp-handler/mcp'; | ||
| * | ||
| * const server = new McpServer({ name: 'my-store' }); | ||
| * const handlers = createHandlers({ | ||
| * baseUrl: 'https://mystore.com', | ||
| * headers: { 'Authorization': 'Bearer secret' } | ||
| * }); | ||
| * | ||
| * // Customize tool definitions | ||
| * server.registerTool( | ||
| * 'search_products', | ||
| * { | ||
| * ...tools.searchProducts, | ||
| * description: 'Search our awesome product catalog!', | ||
| * _meta: { | ||
| * 'openai/outputTemplate': 'ui://widget/custom-products.html' | ||
| * } | ||
| * }, | ||
| * handlers.searchProducts | ||
| * ); | ||
| * | ||
| * // Or use custom handler logic | ||
| * server.registerTool( | ||
| * 'create_checkout', | ||
| * tools.createCheckout, | ||
| * async (input) => { | ||
| * // Custom logic before calling API | ||
| * console.log('Creating checkout:', input); | ||
| * const result = await handlers.createCheckout(input); | ||
| * // Custom logic after | ||
| * return result; | ||
| * } | ||
| * ); | ||
| * ``` | ||
| * | ||
| * @module mcp | ||
| */ | ||
|
|
||
| export { createHandlers, type HandlerConfig, type Handlers } from "./handlers"; | ||
| export type { MCPToolDefinition } from "./tools"; | ||
| export { tools } from "./tools"; |
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
updateCheckouthandler uses HTTP methodPATCH, but the ACP API expectsPOSTfor checkout updates. This will cause update operations to fail.View Details
📝 Patch Details
Analysis
HTTP method mismatch in
updateCheckouthandler causes 405 Method Not Allowed errorsWhat fails: The
updateCheckouthandler inpackages/sdk/src/mcp/handlers.tsline 114 usesmethod: "PATCH"to call/api/checkout/:id, but the API route only exports{ GET, POST }methods.How to reproduce:
updateCheckouthandler with a session ID/api/checkout/{session_id}createNextCatchAll) only exports GET and POSTResult: Next.js returns
405 Method Not Allowedper Next.js route handler documentation, causing all checkout update operations to fail.Expected: Should use POST method, matching the API implementation in
packages/sdk/src/next/index.ts(lines 66-72) which routesPOST /:idrequests to the update handler, and consistent with the example implementation inexamples/chat-sdk/lib/ai/tools/update-checkout.tsline 75 which explicitly uses POST.Fixed:
method: "PATCH"tomethod: "POST"inpackages/sdk/src/mcp/handlers.tsline 114PATCH /api/checkout/:idtoPOST /api/checkout/:idinpackages/sdk/src/mcp/tools.tsline 100