-
Notifications
You must be signed in to change notification settings - Fork 3
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
Draft
blurrah
wants to merge
5
commits into
main
Choose a base branch
from
mcp-helpers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+512
−2
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e0281f6
feat: add MCP tools and complete product feed spec
blurrah e9c53f9
fix(mcp): correct HTTP method for updateCheckout
blurrah 4d3b06b
feat(mcp): add payment fallback for MCP context
blurrah e1347e2
fix(mcp): remove optional on zod schema if default is set
blurrah e284a55
refactor(mcp): simplify to single getCheckoutUrl function
blurrah File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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), | ||
| }); | ||
| }, | ||
|
|
||
| /** | ||
| * 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>; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 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/namevscustomer.billing_address/shipping_address,fulfillment.selected_option_idvsfulfillment.selected_id,payment.tokenvspayment.delegated_token).View Details
📝 Patch Details
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:
/api/checkoutCreateCheckoutSessionSchemawhich expectscustomer.shipping_addressandfulfillment.selected_idemail,name,selected_option_id,address) and passes empty objectsResult: ACP handler receives
customer: {}andfulfillment: {}. Theproducts.price()function checks!!customer?.shipping_addressand!!fulfillment?.selected_id(seeexamples/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.tokengets stripped instead of being mapped topayment.delegated_token.Expected: MCP handlers should transform data to match ACP schema before sending requests, mapping
customer.email/name+fulfillment.address→customer.shipping_address,fulfillment.selected_option_id→fulfillment.selected_id, andpayment.token→payment.delegated_token.Fix: Added transformation functions
transformToACP()andtransformPayment()in handlers.ts that convert MCP schema to ACP schema before API requests.