Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
"commerce",
"checkout",
"product-feed",
"mcp",
"model-context-protocol",
"ai",
"chatgpt",
"openai",
Expand Down Expand Up @@ -49,6 +51,10 @@
"types": "./dist/feed/next/index.d.ts",
"import": "./dist/feed/next/index.js"
},
"./mcp": {
"types": "./dist/mcp/index.d.ts",
"import": "./dist/mcp/index.js"
},
"./test": {
"types": "./dist/test/index.d.ts",
"import": "./dist/test/index.js"
Expand Down
11 changes: 9 additions & 2 deletions packages/sdk/src/feed/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,9 @@ export const ProductFeedItemSchema = z.object({
// Availability & Inventory
availability_date: z.string().datetime().optional(),
expiration_date: z.string().datetime().optional(),
pickup_method: z.enum(["buy_online_pickup_in_store", "curbside", "in_store"]).optional(),
pickup_method: z
.enum(["buy_online_pickup_in_store", "curbside", "in_store"])
.optional(),
pickup_sla: z.string().optional(), // e.g., "1 hour", "same day"

// Variants & Item Groups
Expand Down Expand Up @@ -232,7 +234,12 @@ export const ProductFeedItemSchema = z.object({
// Related Products
related_product_ids: z.array(z.string()).optional(),
relationship_type: z
.enum(["often_bought_with", "similar_to", "accessories_for", "alternative_to"])
.enum([
"often_bought_with",
"similar_to",
"accessories_for",
"alternative_to",
])
.optional(),

// Reviews & Q&A
Expand Down
184 changes: 184 additions & 0 deletions packages/sdk/src/mcp/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/**
* 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;

/**
* Function to generate checkout URL for a session.
* Used when completeCheckout is called without a payment token (MCP context).
* Defaults to `${baseUrl}/checkout/${sessionId}` if not provided.
*
* @example
* ```typescript
* getCheckoutUrl: (sessionId) => `https://mystore.com/checkout/${sessionId}`
* ```
*/
getCheckoutUrl?: (sessionId: string) => string;
}

/**
* 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: "POST",
body: JSON.stringify(body),
});
Comment on lines +113 to +128
Copy link

Choose a reason for hiding this comment

The 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., customer.email/name vs customer.billing_address/shipping_address, fulfillment.selected_option_id vs fulfillment.selected_id, payment.token vs payment.delegated_token).

View Details
📝 Patch Details
diff --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),
 			});
 		},
 

Analysis

Schema mismatch between MCP handlers and ACP API prevents checkout completion

What fails: MCP handlers in packages/sdk/src/mcp/handlers.ts (createCheckout, updateCheckout, completeCheckout) send data in MCP tool schema format that gets silently stripped by ACP schema validation, preventing checkouts from becoming ready for payment.

How to reproduce:

  1. Use MCP createCheckout tool with customer and fulfillment data:
{
  customer: { email: "[email protected]", name: "John Doe" },
  fulfillment: { 
    selected_option_id: "express",
    address: { line1: "123 Main", city: "Seattle", postal_code: "98101", country: "US" }
  }
}
  1. MCP handler sends this directly to ACP API at /api/checkout
  2. ACP validates with CreateCheckoutSessionSchema which expects customer.shipping_address and fulfillment.selected_id
  3. Zod strips unknown fields (email, name, selected_option_id, address) and passes empty objects

Result: ACP handler receives customer: {} and fulfillment: {}. The products.price() function checks !!customer?.shipping_address and !!fulfillment?.selected_id (see examples/chat-sdk/lib/store/products.ts:105-108), both evaluate to false, so checkout status remains "not_ready_for_payment" forever. Same issue with completeCheckout: payment.token gets stripped instead of being mapped to payment.delegated_token.

Expected: MCP handlers should transform data to match ACP schema before sending requests, mapping customer.email/name + fulfillment.addresscustomer.shipping_address, fulfillment.selected_option_idfulfillment.selected_id, and payment.tokenpayment.delegated_token.

Fix: Added transformation functions transformToACP() and transformPayment() in handlers.ts that convert MCP schema to ACP schema before API requests.

},

/**
* Complete a checkout session and process payment.
* In MCP context (no payment token), returns checkout URL for user to complete payment.
* In ACP context (with payment token), processes payment directly.
*/
completeCheckout: async (input: any): Promise<unknown> => {
const { session_id, customer, payment } = input;

// MCP context: no payment token provided
// Return checkout URL for user to complete payment on merchant site
if (!payment?.token) {
const checkoutUrl = config.getCheckoutUrl
? config.getCheckoutUrl(session_id)
: `${config.baseUrl}/checkout/${session_id}`;

return {
checkout_url: checkoutUrl,
session_id,
status: "pending_payment",
message: "Complete your purchase at the checkout link",
};
}

// ACP context: payment token provided
// Process payment through ACP complete endpoint
return request(`/api/checkout/${session_id}/complete`, {
method: "POST",
body: JSON.stringify({ customer, payment }),
});
},

/**
* 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>;
91 changes: 91 additions & 0 deletions packages/sdk/src/mcp/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/**
* 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.
*
* ## Payment Handling
*
* MCP tools follow the same ACP protocol as the full ACP implementation, but with
* a key difference: ChatGPT Apps don't provide delegated payment tokens. When
* `completeCheckout` is called without a payment token, it returns a checkout URL
* for the user to complete payment on your site (which can be loaded in the ChatGPT
* iframe if desired).
*
* @example Basic usage (default checkout URL)
* ```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'
* // Defaults to: https://mystore.com/checkout/:sessionId
* });
*
* // 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 custom checkout URL
* ```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' },
* getCheckoutUrl: (sessionId) => `https://mystore.com/buy/${sessionId}?source=chatgpt`
* });
*
* // Register 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);
* ```
*
* @example With custom handler logic
* ```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',
* getCheckoutUrl: (sessionId) => `https://mystore.com/checkout/${sessionId}`
* });
*
* // Customize tool definitions
* server.registerTool(
* 'search_products',
* {
* ...tools.searchProducts,
* description: 'Search our awesome product catalog!',
* },
* handlers.searchProducts
* );
*
* // Or wrap handlers with custom logic
* server.registerTool(
* 'create_checkout',
* tools.createCheckout,
* async (input) => {
* console.log('Creating checkout:', input);
* const result = await handlers.createCheckout(input);
* return result;
* }
* );
* ```
*
* @module mcp
*/

export { createHandlers, type HandlerConfig, type Handlers } from "./handlers";
export type { MCPToolDefinition } from "./tools";
export { tools } from "./tools";
Loading