From 79374fd11b48ad2c96097184b492b6f6f7710593 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Nov 2025 03:44:26 +0000 Subject: [PATCH 01/16] chore(mcp): clarify http auth error --- packages/mcp-server/src/headers.ts | 4 +++- packages/mcp-server/src/http.ts | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/mcp-server/src/headers.ts b/packages/mcp-server/src/headers.ts index 5a76983..ee22980 100644 --- a/packages/mcp-server/src/headers.ts +++ b/packages/mcp-server/src/headers.ts @@ -11,7 +11,9 @@ export const parseAuthHeaders = (req: IncomingMessage): Partial = case 'Bearer': return { accessToken: req.headers.authorization.slice('Bearer '.length) }; default: - throw new Error(`Unsupported authorization scheme`); + throw new Error( + 'Unsupported authorization scheme. Expected the "Authorization" header to be a supported scheme (Bearer).', + ); } } diff --git a/packages/mcp-server/src/http.ts b/packages/mcp-server/src/http.ts index ae88c77..d078bf8 100644 --- a/packages/mcp-server/src/http.ts +++ b/packages/mcp-server/src/http.ts @@ -52,7 +52,7 @@ const newServer = ({ }, mcpOptions, }); - } catch { + } catch (error) { const resourceIdentifier = oauthResourceIdentifier(req); res.set( 'WWW-Authenticate', @@ -62,7 +62,7 @@ const newServer = ({ jsonrpc: '2.0', error: { code: -32000, - message: 'Unauthorized', + message: `Unauthorized: ${error instanceof Error ? error.message : error}`, }, }); return null; From cadbf3111d4aff52467527cbad99abba90164cc8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 13 Nov 2025 03:34:35 +0000 Subject: [PATCH 02/16] fix(mcp): return tool execution error on jq failure --- packages/mcp-server/src/filtering.ts | 4 ++++ packages/mcp-server/src/tools/types.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/packages/mcp-server/src/filtering.ts b/packages/mcp-server/src/filtering.ts index 1aa9a40..eaae0fc 100644 --- a/packages/mcp-server/src/filtering.ts +++ b/packages/mcp-server/src/filtering.ts @@ -12,3 +12,7 @@ export async function maybeFilter(jqFilter: unknown | undefined, response: any): async function jq(json: any, jqFilter: string) { return (await initJq).json(json, jqFilter); } + +export function isJqError(error: any): error is Error { + return error instanceof Error && 'stderr' in error; +} diff --git a/packages/mcp-server/src/tools/types.ts b/packages/mcp-server/src/tools/types.ts index d484ddf..120ee5b 100644 --- a/packages/mcp-server/src/tools/types.ts +++ b/packages/mcp-server/src/tools/types.ts @@ -87,6 +87,18 @@ export async function asBinaryContentResult(response: Response): Promise Date: Thu, 13 Nov 2025 03:37:12 +0000 Subject: [PATCH 03/16] chore(mcp): upgrade jq-web --- packages/mcp-server/package.json | 2 +- packages/mcp-server/yarn.lock | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 529f4fe..99be856 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -38,7 +38,7 @@ "date-fns": "^4.1.0", "express": "^5.1.0", "fuse.js": "^7.1.0", - "jq-web": "https://github.com/stainless-api/jq-web/releases/download/v0.8.6/jq-web.tar.gz", + "jq-web": "https://github.com/stainless-api/jq-web/releases/download/v0.8.8/jq-web.tar.gz", "qs": "^6.14.0", "typescript": "5.8.3", "yargs": "^17.7.2", diff --git a/packages/mcp-server/yarn.lock b/packages/mcp-server/yarn.lock index c68955e..fa352d6 100644 --- a/packages/mcp-server/yarn.lock +++ b/packages/mcp-server/yarn.lock @@ -2740,9 +2740,9 @@ jest@^29.4.0: import-local "^3.0.2" jest-cli "^29.7.0" -"jq-web@https://github.com/stainless-api/jq-web/releases/download/v0.8.6/jq-web.tar.gz": - version "0.8.6" - resolved "https://github.com/stainless-api/jq-web/releases/download/v0.8.6/jq-web.tar.gz#14d0e126987736e82e964d675c3838b5944faa6f" +"jq-web@https://github.com/stainless-api/jq-web/releases/download/v0.8.8/jq-web.tar.gz": + version "0.8.8" + resolved "https://github.com/stainless-api/jq-web/releases/download/v0.8.8/jq-web.tar.gz#7849ef64bdfc28f70cbfc9888f886860e96da10d" js-tokens@^4.0.0: version "4.0.0" From 94efb539eb6279bd5e8076e9652aaac821d7e465 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 26 Nov 2025 03:45:34 +0000 Subject: [PATCH 04/16] feat(mcp): add detail field to docs search tool --- packages/mcp-server/src/docs-search-tool.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/mcp-server/src/docs-search-tool.ts b/packages/mcp-server/src/docs-search-tool.ts index eb89849..917f2c1 100644 --- a/packages/mcp-server/src/docs-search-tool.ts +++ b/packages/mcp-server/src/docs-search-tool.ts @@ -13,8 +13,7 @@ export const metadata: Metadata = { export const tool: Tool = { name: 'search_docs', - description: - 'Search for documentation for how to use the client to interact with the API.\nThe tool will return an array of Markdown-formatted documentation pages.', + description: 'Search for documentation for how to use the client to interact with the API.', inputSchema: { type: 'object', properties: { @@ -25,7 +24,12 @@ export const tool: Tool = { language: { type: 'string', description: 'The language for the SDK to search for.', - enum: ['http', 'python', 'go', 'typescript', 'terraform', 'ruby', 'java', 'kotlin'], + enum: ['http', 'python', 'go', 'typescript', 'javascript', 'terraform', 'ruby', 'java', 'kotlin'], + }, + detail: { + type: 'string', + description: 'The amount of detail to return.', + enum: ['default', 'verbose'], }, }, required: ['query', 'language'], From 6ecc636c5e0c2a2aeaed7da6e57a1663b3d711e7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Dec 2025 04:09:23 +0000 Subject: [PATCH 05/16] chore(client): fix logger property type --- src/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client.ts b/src/client.ts index e5f4f33..2c38c0b 100644 --- a/src/client.ts +++ b/src/client.ts @@ -155,7 +155,7 @@ export class BeeperDesktop { baseURL: string; maxRetries: number; timeout: number; - logger: Logger | undefined; + logger: Logger; logLevel: LogLevel | undefined; fetchOptions: MergedRequestInit | undefined; From 7886dae7ae5da785ef4bea988f253e35007ee16a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Dec 2025 04:18:53 +0000 Subject: [PATCH 06/16] fix(mcp): return tool execution error on api error --- .../mcp-server/src/tools/accounts/get-accounts.ts | 11 +++++++++-- packages/mcp-server/src/tools/chats/get-chat.ts | 11 +++++++++-- packages/mcp-server/src/tools/chats/search-chats.ts | 11 +++++++++-- .../mcp-server/src/tools/messages/list-messages.ts | 11 +++++++++-- .../mcp-server/src/tools/messages/search-messages.ts | 11 +++++++++-- .../mcp-server/src/tools/messages/send-message.ts | 11 +++++++++-- packages/mcp-server/src/tools/top-level/focus-app.ts | 11 +++++++++-- packages/mcp-server/src/tools/top-level/search.ts | 11 +++++++++-- 8 files changed, 72 insertions(+), 16 deletions(-) diff --git a/packages/mcp-server/src/tools/accounts/get-accounts.ts b/packages/mcp-server/src/tools/accounts/get-accounts.ts index 85fe44c..84f2cb6 100644 --- a/packages/mcp-server/src/tools/accounts/get-accounts.ts +++ b/packages/mcp-server/src/tools/accounts/get-accounts.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -28,7 +28,14 @@ export const tool: Tool = { }; export const handler = async (client: BeeperDesktop, args: Record | undefined) => { - return asTextContentResult(await client.accounts.list()); + try { + return asTextContentResult(await client.accounts.list()); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/tools/chats/get-chat.ts b/packages/mcp-server/src/tools/chats/get-chat.ts index 39c432a..d5b6e74 100644 --- a/packages/mcp-server/src/tools/chats/get-chat.ts +++ b/packages/mcp-server/src/tools/chats/get-chat.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -39,7 +39,14 @@ export const tool: Tool = { export const handler = async (client: BeeperDesktop, args: Record | undefined) => { const { chatID, ...body } = args as any; - return asTextContentResult(await client.chats.retrieve(chatID, body)); + try { + return asTextContentResult(await client.chats.retrieve(chatID, body)); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/tools/chats/search-chats.ts b/packages/mcp-server/src/tools/chats/search-chats.ts index f624726..7adeab5 100644 --- a/packages/mcp-server/src/tools/chats/search-chats.ts +++ b/packages/mcp-server/src/tools/chats/search-chats.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -98,7 +98,14 @@ export const tool: Tool = { export const handler = async (client: BeeperDesktop, args: Record | undefined) => { const body = args as any; const response = await client.chats.search(body).asResponse(); - return asTextContentResult(await response.json()); + try { + return asTextContentResult(await response.json()); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/tools/messages/list-messages.ts b/packages/mcp-server/src/tools/messages/list-messages.ts index 4b91ed5..f9840dc 100644 --- a/packages/mcp-server/src/tools/messages/list-messages.ts +++ b/packages/mcp-server/src/tools/messages/list-messages.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -45,7 +45,14 @@ export const tool: Tool = { export const handler = async (client: BeeperDesktop, args: Record | undefined) => { const { chatID, ...body } = args as any; const response = await client.messages.list(chatID, body).asResponse(); - return asTextContentResult(await response.json()); + try { + return asTextContentResult(await response.json()); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/tools/messages/search-messages.ts b/packages/mcp-server/src/tools/messages/search-messages.ts index b3392ba..89ae4d8 100644 --- a/packages/mcp-server/src/tools/messages/search-messages.ts +++ b/packages/mcp-server/src/tools/messages/search-messages.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -117,7 +117,14 @@ export const tool: Tool = { export const handler = async (client: BeeperDesktop, args: Record | undefined) => { const body = args as any; const response = await client.messages.search(body).asResponse(); - return asTextContentResult(await response.json()); + try { + return asTextContentResult(await response.json()); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/tools/messages/send-message.ts b/packages/mcp-server/src/tools/messages/send-message.ts index 9aff7a8..bf9b5ee 100644 --- a/packages/mcp-server/src/tools/messages/send-message.ts +++ b/packages/mcp-server/src/tools/messages/send-message.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -41,7 +41,14 @@ export const tool: Tool = { export const handler = async (client: BeeperDesktop, args: Record | undefined) => { const { chatID, ...body } = args as any; - return asTextContentResult(await client.messages.send(chatID, body)); + try { + return asTextContentResult(await client.messages.send(chatID, body)); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/tools/top-level/focus-app.ts b/packages/mcp-server/src/tools/top-level/focus-app.ts index e308e6b..f1c5e76 100644 --- a/packages/mcp-server/src/tools/top-level/focus-app.ts +++ b/packages/mcp-server/src/tools/top-level/focus-app.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -46,7 +46,14 @@ export const tool: Tool = { export const handler = async (client: BeeperDesktop, args: Record | undefined) => { const body = args as any; - return asTextContentResult(await client.focus(body)); + try { + return asTextContentResult(await client.focus(body)); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; diff --git a/packages/mcp-server/src/tools/top-level/search.ts b/packages/mcp-server/src/tools/top-level/search.ts index ce1bdfb..52c575e 100644 --- a/packages/mcp-server/src/tools/top-level/search.ts +++ b/packages/mcp-server/src/tools/top-level/search.ts @@ -1,6 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { Metadata, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; +import { Metadata, asErrorResult, asTextContentResult } from '@beeper/desktop-mcp/tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; import BeeperDesktop from '@beeper/desktop-api'; @@ -35,7 +35,14 @@ export const tool: Tool = { export const handler = async (client: BeeperDesktop, args: Record | undefined) => { const body = args as any; - return asTextContentResult(await client.search(body)); + try { + return asTextContentResult(await client.search(body)); + } catch (error) { + if (error instanceof BeeperDesktop.APIError) { + return asErrorResult(error.message); + } + throw error; + } }; export default { metadata, tool, handler }; From d635e28ce32796e0e71b8ee21a579fbca061f1f5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Dec 2025 04:21:24 +0000 Subject: [PATCH 07/16] feat(mcp): return logs on code tool errors --- packages/mcp-server/src/code-tool-types.ts | 6 ++++- packages/mcp-server/src/code-tool-worker.ts | 6 +++++ packages/mcp-server/src/code-tool.ts | 25 +++++++++++++++++++-- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/packages/mcp-server/src/code-tool-types.ts b/packages/mcp-server/src/code-tool-types.ts index 8866460..42c8bb7 100644 --- a/packages/mcp-server/src/code-tool-types.ts +++ b/packages/mcp-server/src/code-tool-types.ts @@ -11,4 +11,8 @@ export type WorkerSuccess = { logLines: string[]; errLines: string[]; }; -export type WorkerError = { message: string | undefined }; +export type WorkerError = { + message: string | undefined; + logLines: string[]; + errLines: string[]; +}; diff --git a/packages/mcp-server/src/code-tool-worker.ts b/packages/mcp-server/src/code-tool-worker.ts index aee55b5..5ce7e16 100644 --- a/packages/mcp-server/src/code-tool-worker.ts +++ b/packages/mcp-server/src/code-tool-worker.ts @@ -157,6 +157,8 @@ const fetch = async (req: Request): Promise => { { message: 'The code param is missing. Provide one containing a top-level `run` function. Write code within this template:\n\n```\nasync function run(client) {\n // Fill this out\n}\n```', + logLines: [], + errLines: [], } satisfies WorkerError, { status: 400, statusText: 'Code execution error' }, ); @@ -168,6 +170,8 @@ const fetch = async (req: Request): Promise => { { message: 'The code is missing a top-level `run` function. Write code within this template:\n\n```\nasync function run(client) {\n // Fill this out\n}\n```', + logLines: [], + errLines: [], } satisfies WorkerError, { status: 400, statusText: 'Code execution error' }, ); @@ -200,6 +204,8 @@ const fetch = async (req: Request): Promise => { return Response.json( { message: parseError(code, e), + logLines, + errLines, } satisfies WorkerError, { status: 400, statusText: 'Code execution error' }, ); diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index fecf110..ad953bb 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -132,9 +132,30 @@ export async function codeTool(): Promise { content: [returnOutput, logOutput, errOutput].filter((block) => block !== null), }; } else { - const { message } = (await resp.json()) as WorkerError; + const { message, logLines, errLines } = (await resp.json()) as WorkerError; + const messageOutput: ContentBlock | null = + message == null ? null : ( + { + type: 'text', + text: message, + } + ); + const logOutput: ContentBlock | null = + logLines.length === 0 ? + null + : { + type: 'text', + text: logLines.join('\n'), + }; + const errOutput: ContentBlock | null = + errLines.length === 0 ? + null + : { + type: 'text', + text: 'Error output:\n' + errLines.join('\n'), + }; return { - content: message == null ? [] : [{ type: 'text', text: message }], + content: [messageOutput, logOutput, errOutput].filter((block) => block !== null), isError: true, }; } From 7256acf2e8fdd02aae2b169e15547fddb10fb250 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 3 Dec 2025 04:01:35 +0000 Subject: [PATCH 08/16] chore(internal): upgrade eslint --- package.json | 2 +- yarn.lock | 150 ++++++++++++++++++++++++++++++--------------------- 2 files changed, 89 insertions(+), 63 deletions(-) diff --git a/package.json b/package.json index ed69a18..fa42669 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "@types/node": "^20.17.6", "@typescript-eslint/eslint-plugin": "8.31.1", "@typescript-eslint/parser": "8.31.1", - "eslint": "^9.20.1", + "eslint": "^9.39.1", "eslint-plugin-prettier": "^5.4.1", "eslint-plugin-unused-imports": "^4.1.4", "iconv-lite": "^0.6.3", diff --git a/yarn.lock b/yarn.lock index 8311caf..5f56a20 100644 --- a/yarn.lock +++ b/yarn.lock @@ -350,45 +350,52 @@ dependencies: "@cspotcode/source-map-consumer" "0.8.0" -"@eslint-community/eslint-utils@^4.2.0", "@eslint-community/eslint-utils@^4.4.0": +"@eslint-community/eslint-utils@^4.4.0": version "4.4.0" resolved "https://registry.yarnpkg.com/@eslint-community/eslint-utils/-/eslint-utils-4.4.0.tgz#a23514e8fb9af1269d5f7788aa556798d61c6b59" integrity sha512-1/sA4dwrzBAyeUoQ6oxahHKmrZvsnLCg4RfxW3ZFGGmQkSNQPFNLV9CUEFQP1x9EYXHTo5p6xdhZM1Ne9p/AfA== dependencies: eslint-visitor-keys "^3.3.0" +"@eslint-community/eslint-utils@^4.8.0": + version "4.9.0" + resolved "https://registry.yarnpkg.com/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz#7308df158e064f0dd8b8fdb58aa14fa2a7f913b3" + integrity sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g== + dependencies: + eslint-visitor-keys "^3.4.3" + "@eslint-community/regexpp@^4.10.0", "@eslint-community/regexpp@^4.12.1": version "4.12.1" resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.12.1.tgz#cfc6cffe39df390a3841cde2abccf92eaa7ae0e0" integrity sha512-CCZCDJuduB9OUkFkY2IgppNZMi2lBQgD2qzwXkEia16cge2pijY/aXi96CJMquDMn3nJdlPV1A5KrJEXwfLNzQ== -"@eslint/config-array@^0.19.0": - version "0.19.2" - resolved "https://registry.yarnpkg.com/@eslint/config-array/-/config-array-0.19.2.tgz#3060b809e111abfc97adb0bb1172778b90cb46aa" - integrity sha512-GNKqxfHG2ySmJOBSHg7LxeUx4xpuCoFjacmlCoYWEbaPXLwvfIjixRI12xCQZeULksQb23uiA8F40w5TojpV7w== +"@eslint/config-array@^0.21.1": + version "0.21.1" + resolved "https://registry.yarnpkg.com/@eslint/config-array/-/config-array-0.21.1.tgz#7d1b0060fea407f8301e932492ba8c18aff29713" + integrity sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA== dependencies: - "@eslint/object-schema" "^2.1.6" + "@eslint/object-schema" "^2.1.7" debug "^4.3.1" minimatch "^3.1.2" -"@eslint/core@^0.10.0": - version "0.10.0" - resolved "https://registry.yarnpkg.com/@eslint/core/-/core-0.10.0.tgz#23727063c21b335f752dbb3a16450f6f9cbc9091" - integrity sha512-gFHJ+xBOo4G3WRlR1e/3G8A6/KZAH6zcE/hkLRCZTi/B9avAG365QhFA8uOGzTMqgTghpn7/fSnscW++dpMSAw== +"@eslint/config-helpers@^0.4.2": + version "0.4.2" + resolved "https://registry.yarnpkg.com/@eslint/config-helpers/-/config-helpers-0.4.2.tgz#1bd006ceeb7e2e55b2b773ab318d300e1a66aeda" + integrity sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw== dependencies: - "@types/json-schema" "^7.0.15" + "@eslint/core" "^0.17.0" -"@eslint/core@^0.11.0": - version "0.11.0" - resolved "https://registry.yarnpkg.com/@eslint/core/-/core-0.11.0.tgz#7a9226e850922e42cbd2ba71361eacbe74352a12" - integrity sha512-DWUB2pksgNEb6Bz2fggIy1wh6fGgZP4Xyy/Mt0QZPiloKKXerbqq9D3SBQTlCRYOrcRPu4vuz+CGjwdfqxnoWA== +"@eslint/core@^0.17.0": + version "0.17.0" + resolved "https://registry.yarnpkg.com/@eslint/core/-/core-0.17.0.tgz#77225820413d9617509da9342190a2019e78761c" + integrity sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ== dependencies: "@types/json-schema" "^7.0.15" -"@eslint/eslintrc@^3.2.0": - version "3.2.0" - resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.2.0.tgz#57470ac4e2e283a6bf76044d63281196e370542c" - integrity sha512-grOjVNN8P3hjJn/eIETF1wwd12DdnwFDoyceUJLYYdkpbwq3nLi+4fqrTAONx7XDALqlL220wC/RHSC/QTI/0w== +"@eslint/eslintrc@^3.3.1": + version "3.3.3" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.3.3.tgz#26393a0806501b5e2b6a43aa588a4d8df67880ac" + integrity sha512-Kr+LPIUVKz2qkx1HAMH8q1q6azbqBAsXJUxBl/ODDuVPX45Z9DfwB8tPjTi6nNZ8BuM3nbJxC5zCAg5elnBUTQ== dependencies: ajv "^6.12.4" debug "^4.3.2" @@ -396,26 +403,26 @@ globals "^14.0.0" ignore "^5.2.0" import-fresh "^3.2.1" - js-yaml "^4.1.0" + js-yaml "^4.1.1" minimatch "^3.1.2" strip-json-comments "^3.1.1" -"@eslint/js@9.20.0": - version "9.20.0" - resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.20.0.tgz#7421bcbe74889fcd65d1be59f00130c289856eb4" - integrity sha512-iZA07H9io9Wn836aVTytRaNqh00Sad+EamwOVJT12GTLw1VGMFV/4JaME+JjLtr9fiGaoWgYnS54wrfWsSs4oQ== +"@eslint/js@9.39.1": + version "9.39.1" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.39.1.tgz#0dd59c3a9f40e3f1882975c321470969243e0164" + integrity sha512-S26Stp4zCy88tH94QbBv3XCuzRQiZ9yXofEILmglYTh/Ug/a9/umqvgFtYBAo3Lp0nsI/5/qH1CCrbdK3AP1Tw== -"@eslint/object-schema@^2.1.6": - version "2.1.6" - resolved "https://registry.yarnpkg.com/@eslint/object-schema/-/object-schema-2.1.6.tgz#58369ab5b5b3ca117880c0f6c0b0f32f6950f24f" - integrity sha512-RBMg5FRL0I0gs51M/guSAj5/e14VQ4tpZnQNWwuDT66P14I43ItmPfIZRhO9fUVIPOAQXU47atlywZ/czoqFPA== +"@eslint/object-schema@^2.1.7": + version "2.1.7" + resolved "https://registry.yarnpkg.com/@eslint/object-schema/-/object-schema-2.1.7.tgz#6e2126a1347e86a4dedf8706ec67ff8e107ebbad" + integrity sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA== -"@eslint/plugin-kit@^0.2.5": - version "0.2.5" - resolved "https://registry.yarnpkg.com/@eslint/plugin-kit/-/plugin-kit-0.2.5.tgz#ee07372035539e7847ef834e3f5e7b79f09e3a81" - integrity sha512-lB05FkqEdUg2AA0xEbUz0SnkXT1LcCTa438W4IWTUh4hdOnVbQyOJ81OrDXsJk/LSiJHubgGEFoR5EHq1NsH1A== +"@eslint/plugin-kit@^0.4.1": + version "0.4.1" + resolved "https://registry.yarnpkg.com/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz#9779e3fd9b7ee33571a57435cf4335a1794a6cb2" + integrity sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA== dependencies: - "@eslint/core" "^0.10.0" + "@eslint/core" "^0.17.0" levn "^0.4.1" "@humanfs/core@^0.19.1": @@ -441,10 +448,10 @@ resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.3.1.tgz#c72a5c76a9fbaf3488e231b13dc52c0da7bab42a" integrity sha512-JBxkERygn7Bv/GbN5Rv8Ul6LVknS+5Bp6RgDC/O8gEBU/yeH5Ui5C/OlWrTb6qct7LjjfT6Re2NxB0ln0yYybA== -"@humanwhocodes/retry@^0.4.1": - version "0.4.1" - resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.4.1.tgz#9a96ce501bc62df46c4031fbd970e3cc6b10f07b" - integrity sha512-c7hNEllBlenFTHBky65mhq8WD2kbN9Q6gk0bTk8lSBvc554jpXSkST1iePudpt7+A/AQvuHs9EMqjHDXMY1lrA== +"@humanwhocodes/retry@^0.4.2": + version "0.4.3" + resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.4.3.tgz#c2b9d2e374ee62c586d3adbea87199b1d7a7a6ba" + integrity sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ== "@istanbuljs/load-nyc-config@^1.0.0": version "1.1.0" @@ -1057,6 +1064,11 @@ acorn@^8.14.0: resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.14.0.tgz#063e2c70cac5fb4f6467f0b11152e04c682795b0" integrity sha512-cl669nCJTZBsL97OF4kUQm5g5hC2uihk0NxY3WENAC0TYdILVkAyHymAntgxGkl7K+t0cXIrH5siy5S4XkFycA== +acorn@^8.15.0: + version "8.15.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.15.0.tgz#a360898bc415edaac46c8241f6383975b930b816" + integrity sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg== + acorn@^8.4.1: version "8.7.0" resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.7.0.tgz#90951fde0f8f09df93549481e5fc141445b791cf" @@ -1560,15 +1572,15 @@ eslint-plugin-unused-imports@^4.1.4: resolved "https://registry.yarnpkg.com/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.1.4.tgz#62ddc7446ccbf9aa7b6f1f0b00a980423cda2738" integrity sha512-YptD6IzQjDardkl0POxnnRBhU1OEePMV0nd6siHaRBbd+lyh6NAhFEobiznKU7kTsSsDeSD62Pe7kAM1b7dAZQ== -eslint-scope@^8.2.0: - version "8.2.0" - resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-8.2.0.tgz#377aa6f1cb5dc7592cfd0b7f892fd0cf352ce442" - integrity sha512-PHlWUfG6lvPc3yvP5A4PNyBL1W8fkDUccmI21JUu/+GKZBoH/W5u6usENXUrWFRsyoW5ACUjFGgAFQp5gUlb/A== +eslint-scope@^8.4.0: + version "8.4.0" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-8.4.0.tgz#88e646a207fad61436ffa39eb505147200655c82" + integrity sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg== dependencies: esrecurse "^4.3.0" estraverse "^5.2.0" -eslint-visitor-keys@^3.3.0: +eslint-visitor-keys@^3.3.0, eslint-visitor-keys@^3.4.3: version "3.4.3" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== @@ -1578,31 +1590,36 @@ eslint-visitor-keys@^4.2.0: resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-4.2.0.tgz#687bacb2af884fcdda8a6e7d65c606f46a14cd45" integrity sha512-UyLnSehNt62FFhSwjZlHmeokpRK59rcz29j+F1/aDgbkbRTk7wIc9XzdoasMUbRNKDM0qQt/+BJ4BrpFeABemw== -eslint@^9.20.1: - version "9.20.1" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.20.1.tgz#923924c078f5226832449bac86662dd7e53c91d6" - integrity sha512-m1mM33o6dBUjxl2qb6wv6nGNwCAsns1eKtaQ4l/NPHeTvhiUPbtdfMyktxN4B3fgHIgsYh1VT3V9txblpQHq+g== +eslint-visitor-keys@^4.2.1: + version "4.2.1" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz#4cfea60fe7dd0ad8e816e1ed026c1d5251b512c1" + integrity sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ== + +eslint@^9.39.1: + version "9.39.1" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.39.1.tgz#be8bf7c6de77dcc4252b5a8dcb31c2efff74a6e5" + integrity sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g== dependencies: - "@eslint-community/eslint-utils" "^4.2.0" + "@eslint-community/eslint-utils" "^4.8.0" "@eslint-community/regexpp" "^4.12.1" - "@eslint/config-array" "^0.19.0" - "@eslint/core" "^0.11.0" - "@eslint/eslintrc" "^3.2.0" - "@eslint/js" "9.20.0" - "@eslint/plugin-kit" "^0.2.5" + "@eslint/config-array" "^0.21.1" + "@eslint/config-helpers" "^0.4.2" + "@eslint/core" "^0.17.0" + "@eslint/eslintrc" "^3.3.1" + "@eslint/js" "9.39.1" + "@eslint/plugin-kit" "^0.4.1" "@humanfs/node" "^0.16.6" "@humanwhocodes/module-importer" "^1.0.1" - "@humanwhocodes/retry" "^0.4.1" + "@humanwhocodes/retry" "^0.4.2" "@types/estree" "^1.0.6" - "@types/json-schema" "^7.0.15" ajv "^6.12.4" chalk "^4.0.0" cross-spawn "^7.0.6" debug "^4.3.2" escape-string-regexp "^4.0.0" - eslint-scope "^8.2.0" - eslint-visitor-keys "^4.2.0" - espree "^10.3.0" + eslint-scope "^8.4.0" + eslint-visitor-keys "^4.2.1" + espree "^10.4.0" esquery "^1.5.0" esutils "^2.0.2" fast-deep-equal "^3.1.3" @@ -1618,7 +1635,7 @@ eslint@^9.20.1: natural-compare "^1.4.0" optionator "^0.9.3" -espree@^10.0.1, espree@^10.3.0: +espree@^10.0.1: version "10.3.0" resolved "https://registry.yarnpkg.com/espree/-/espree-10.3.0.tgz#29267cf5b0cb98735b65e64ba07e0ed49d1eed8a" integrity sha512-0QYC8b24HWY8zjRnDTL6RiHfDbAWn63qb4LMj1Z4b076A4une81+z03Kg7l7mn/48PUTqoLptSXez8oknU8Clg== @@ -1627,6 +1644,15 @@ espree@^10.0.1, espree@^10.3.0: acorn-jsx "^5.3.2" eslint-visitor-keys "^4.2.0" +espree@^10.4.0: + version "10.4.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-10.4.0.tgz#d54f4949d4629005a1fa168d937c3ff1f7e2a837" + integrity sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ== + dependencies: + acorn "^8.15.0" + acorn-jsx "^5.3.2" + eslint-visitor-keys "^4.2.1" + esprima@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" @@ -2440,10 +2466,10 @@ js-yaml@^3.13.1: argparse "^1.0.7" esprima "^4.0.0" -js-yaml@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" - integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== +js-yaml@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.1.tgz#854c292467705b699476e1a2decc0c8a3458806b" + integrity sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA== dependencies: argparse "^2.0.1" From 6400f79bf4d6fd5bc46a11ccf2336327910a39e9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 5 Dec 2025 03:40:16 +0000 Subject: [PATCH 09/16] chore: use latest @modelcontextprotocol/sdk --- packages/mcp-server/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 99be856..75ec3a3 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -32,7 +32,7 @@ "dependencies": { "@beeper/desktop-api": "file:../../dist/", "@cloudflare/cabidela": "^0.2.4", - "@modelcontextprotocol/sdk": "^1.11.5", + "@modelcontextprotocol/sdk": "^1.24.0", "@valtown/deno-http-worker": "^0.0.21", "cors": "^2.8.5", "date-fns": "^4.1.0", From dd5606aeb6f72a2b7383a7a52d47a3786adb7fe8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 5 Dec 2025 03:45:54 +0000 Subject: [PATCH 10/16] feat(mcp): add typescript check to code execution tool --- packages/mcp-server/src/code-tool-worker.ts | 107 ++++++++++++++++---- packages/mcp-server/src/code-tool.ts | 16 ++- 2 files changed, 100 insertions(+), 23 deletions(-) diff --git a/packages/mcp-server/src/code-tool-worker.ts b/packages/mcp-server/src/code-tool-worker.ts index 5ce7e16..1c3aa69 100644 --- a/packages/mcp-server/src/code-tool-worker.ts +++ b/packages/mcp-server/src/code-tool-worker.ts @@ -1,5 +1,6 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import path from 'node:path'; import util from 'node:util'; import Fuse from 'fuse.js'; @@ -8,30 +9,41 @@ import ts from 'typescript'; import { WorkerInput, WorkerSuccess, WorkerError } from './code-tool-types'; import { BeeperDesktop } from '@beeper/desktop-api'; -function getRunFunctionNode( - code: string, -): ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction | null { +function getRunFunctionSource(code: string): { + type: 'declaration' | 'expression'; + client: string | undefined; + code: string; +} | null { const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true); + const printer = ts.createPrinter(); for (const statement of sourceFile.statements) { // Check for top-level function declarations if (ts.isFunctionDeclaration(statement)) { if (statement.name?.text === 'run') { - return statement; + return { + type: 'declaration', + client: statement.parameters[0]?.name.getText(), + code: printer.printNode(ts.EmitHint.Unspecified, statement.body!, sourceFile), + }; } } // Check for variable declarations: const run = () => {} or const run = function() {} if (ts.isVariableStatement(statement)) { for (const declaration of statement.declarationList.declarations) { - if (ts.isIdentifier(declaration.name) && declaration.name.text === 'run') { + if ( + ts.isIdentifier(declaration.name) && + declaration.name.text === 'run' && // Check if it's initialized with a function - if ( - declaration.initializer && - (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer)) - ) { - return declaration.initializer; - } + declaration.initializer && + (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer)) + ) { + return { + type: 'expression', + client: declaration.initializer.parameters[0]?.name.getText(), + code: printer.printNode(ts.EmitHint.Unspecified, declaration.initializer, sourceFile), + }; } } } @@ -40,6 +52,61 @@ function getRunFunctionNode( return null; } +function getTSDiagnostics(code: string): string[] { + const functionSource = getRunFunctionSource(code)!; + const codeWithImport = [ + 'import { BeeperDesktop } from "@beeper/desktop-api";', + functionSource.type === 'declaration' ? + `async function run(${functionSource.client}: BeeperDesktop)` + : `const run: (${functionSource.client}: BeeperDesktop) => Promise =`, + functionSource.code, + ].join('\n'); + const sourcePath = path.resolve('code.ts'); + const ast = ts.createSourceFile(sourcePath, codeWithImport, ts.ScriptTarget.Latest, true); + const options = ts.getDefaultCompilerOptions(); + options.target = ts.ScriptTarget.Latest; + options.module = ts.ModuleKind.NodeNext; + options.moduleResolution = ts.ModuleResolutionKind.NodeNext; + const host = ts.createCompilerHost(options, true); + const newHost: typeof host = { + ...host, + getSourceFile: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return ast; + } + return host.getSourceFile(...args); + }, + readFile: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return codeWithImport; + } + return host.readFile(...args); + }, + fileExists: (...args) => { + if (path.resolve(args[0]) === sourcePath) { + return true; + } + return host.fileExists(...args); + }, + }; + const program = ts.createProgram({ + options, + rootNames: [sourcePath], + host: newHost, + }); + const diagnostics = ts.getPreEmitDiagnostics(program, ast); + return diagnostics.map((d) => { + const message = ts.flattenDiagnosticMessageText(d.messageText, '\n'); + if (!d.file || !d.start) return `- ${message}`; + const { line: tsLine } = ts.getLineAndCharacterOfPosition(d.file, d.start); + // We add two lines in the beginning, for the client import and the function declaration. + // So the actual (zero-based) line number is tsLine - 2. + const lineNumber = tsLine - 2; + const line = code.split('\n').at(lineNumber)?.trim(); + return line ? `- ${message}\n at line ${lineNumber + 1}\n ${line}` : `- ${message}`; + }); +} + const fuse = new Fuse( [ 'client.focus', @@ -152,11 +219,16 @@ function parseError(code: string, error: unknown): string | undefined { const fetch = async (req: Request): Promise => { const { opts, code } = (await req.json()) as WorkerInput; - if (code == null) { + + const runFunctionSource = code ? getRunFunctionSource(code) : null; + if (!runFunctionSource) { + const message = + code ? + 'The code is missing a top-level `run` function.' + : 'The code argument is missing. Provide one containing a top-level `run` function.'; return Response.json( { - message: - 'The code param is missing. Provide one containing a top-level `run` function. Write code within this template:\n\n```\nasync function run(client) {\n // Fill this out\n}\n```', + message: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``, logLines: [], errLines: [], } satisfies WorkerError, @@ -164,12 +236,11 @@ const fetch = async (req: Request): Promise => { ); } - const runFunctionNode = getRunFunctionNode(code); - if (!runFunctionNode) { + const diagnostics = getTSDiagnostics(code); + if (diagnostics.length > 0) { return Response.json( { - message: - 'The code is missing a top-level `run` function. Write code within this template:\n\n```\nasync function run(client) {\n // Fill this out\n}\n```', + message: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`, logLines: [], errLines: [], } satisfies WorkerError, diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index ad953bb..01307fb 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -1,7 +1,7 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { dirname } from 'node:path'; -import { pathToFileURL } from 'node:url'; +import path from 'node:path'; +import url from 'node:url'; import BeeperDesktop, { ClientOptions } from '@beeper/desktop-api'; import { ContentBlock, Endpoint, Metadata, ToolCallResult } from './tools/types'; @@ -35,10 +35,16 @@ export async function codeTool(): Promise { const baseURLHostname = new URL(client.baseURL).hostname; const { code } = args as { code: string }; - const worker = await newDenoHTTPWorker(pathToFileURL(workerPath), { + const allowRead = [ + 'code-tool-worker.mjs', + `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`, + path.resolve(path.dirname(workerPath), '..'), + ].join(','); + + const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), { runFlags: [ `--node-modules-dir=manual`, - `--allow-read=code-tool-worker.mjs,${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`, + `--allow-read=${allowRead}`, `--allow-net=${baseURLHostname}`, // Allow environment variables because instantiating the client will try to read from them, // even though they are not set. @@ -46,7 +52,7 @@ export async function codeTool(): Promise { ], printOutput: true, spawnOptions: { - cwd: dirname(workerPath), + cwd: path.dirname(workerPath), }, }); From 0583d4a1b97f825d9c3e76c9eae155d09e108f4c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 6 Dec 2025 03:38:30 +0000 Subject: [PATCH 11/16] feat(mcp): handle code mode calls in the Stainless API Moves the code-mode execution to an endpoint in the Stainless API. --- packages/mcp-server/src/code-tool-paths.cts | 3 - packages/mcp-server/src/code-tool-worker.ts | 286 -------------------- packages/mcp-server/src/code-tool.ts | 180 +++--------- packages/mcp-server/src/docs-search-tool.ts | 7 + 4 files changed, 39 insertions(+), 437 deletions(-) delete mode 100644 packages/mcp-server/src/code-tool-paths.cts delete mode 100644 packages/mcp-server/src/code-tool-worker.ts diff --git a/packages/mcp-server/src/code-tool-paths.cts b/packages/mcp-server/src/code-tool-paths.cts deleted file mode 100644 index 15ce7f5..0000000 --- a/packages/mcp-server/src/code-tool-paths.cts +++ /dev/null @@ -1,3 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -export const workerPath = require.resolve('./code-tool-worker.mjs'); diff --git a/packages/mcp-server/src/code-tool-worker.ts b/packages/mcp-server/src/code-tool-worker.ts deleted file mode 100644 index 1c3aa69..0000000 --- a/packages/mcp-server/src/code-tool-worker.ts +++ /dev/null @@ -1,286 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -import path from 'node:path'; -import util from 'node:util'; - -import Fuse from 'fuse.js'; -import ts from 'typescript'; - -import { WorkerInput, WorkerSuccess, WorkerError } from './code-tool-types'; -import { BeeperDesktop } from '@beeper/desktop-api'; - -function getRunFunctionSource(code: string): { - type: 'declaration' | 'expression'; - client: string | undefined; - code: string; -} | null { - const sourceFile = ts.createSourceFile('code.ts', code, ts.ScriptTarget.Latest, true); - const printer = ts.createPrinter(); - - for (const statement of sourceFile.statements) { - // Check for top-level function declarations - if (ts.isFunctionDeclaration(statement)) { - if (statement.name?.text === 'run') { - return { - type: 'declaration', - client: statement.parameters[0]?.name.getText(), - code: printer.printNode(ts.EmitHint.Unspecified, statement.body!, sourceFile), - }; - } - } - - // Check for variable declarations: const run = () => {} or const run = function() {} - if (ts.isVariableStatement(statement)) { - for (const declaration of statement.declarationList.declarations) { - if ( - ts.isIdentifier(declaration.name) && - declaration.name.text === 'run' && - // Check if it's initialized with a function - declaration.initializer && - (ts.isFunctionExpression(declaration.initializer) || ts.isArrowFunction(declaration.initializer)) - ) { - return { - type: 'expression', - client: declaration.initializer.parameters[0]?.name.getText(), - code: printer.printNode(ts.EmitHint.Unspecified, declaration.initializer, sourceFile), - }; - } - } - } - } - - return null; -} - -function getTSDiagnostics(code: string): string[] { - const functionSource = getRunFunctionSource(code)!; - const codeWithImport = [ - 'import { BeeperDesktop } from "@beeper/desktop-api";', - functionSource.type === 'declaration' ? - `async function run(${functionSource.client}: BeeperDesktop)` - : `const run: (${functionSource.client}: BeeperDesktop) => Promise =`, - functionSource.code, - ].join('\n'); - const sourcePath = path.resolve('code.ts'); - const ast = ts.createSourceFile(sourcePath, codeWithImport, ts.ScriptTarget.Latest, true); - const options = ts.getDefaultCompilerOptions(); - options.target = ts.ScriptTarget.Latest; - options.module = ts.ModuleKind.NodeNext; - options.moduleResolution = ts.ModuleResolutionKind.NodeNext; - const host = ts.createCompilerHost(options, true); - const newHost: typeof host = { - ...host, - getSourceFile: (...args) => { - if (path.resolve(args[0]) === sourcePath) { - return ast; - } - return host.getSourceFile(...args); - }, - readFile: (...args) => { - if (path.resolve(args[0]) === sourcePath) { - return codeWithImport; - } - return host.readFile(...args); - }, - fileExists: (...args) => { - if (path.resolve(args[0]) === sourcePath) { - return true; - } - return host.fileExists(...args); - }, - }; - const program = ts.createProgram({ - options, - rootNames: [sourcePath], - host: newHost, - }); - const diagnostics = ts.getPreEmitDiagnostics(program, ast); - return diagnostics.map((d) => { - const message = ts.flattenDiagnosticMessageText(d.messageText, '\n'); - if (!d.file || !d.start) return `- ${message}`; - const { line: tsLine } = ts.getLineAndCharacterOfPosition(d.file, d.start); - // We add two lines in the beginning, for the client import and the function declaration. - // So the actual (zero-based) line number is tsLine - 2. - const lineNumber = tsLine - 2; - const line = code.split('\n').at(lineNumber)?.trim(); - return line ? `- ${message}\n at line ${lineNumber + 1}\n ${line}` : `- ${message}`; - }); -} - -const fuse = new Fuse( - [ - 'client.focus', - 'client.search', - 'client.accounts.list', - 'client.accounts.contacts.search', - 'client.chats.archive', - 'client.chats.create', - 'client.chats.list', - 'client.chats.retrieve', - 'client.chats.search', - 'client.chats.reminders.create', - 'client.chats.reminders.delete', - 'client.messages.list', - 'client.messages.search', - 'client.messages.send', - 'client.assets.download', - ], - { threshold: 1, shouldSort: true }, -); - -function getMethodSuggestions(fullyQualifiedMethodName: string): string[] { - return fuse - .search(fullyQualifiedMethodName) - .map(({ item }) => item) - .slice(0, 5); -} - -const proxyToObj = new WeakMap(); -const objToProxy = new WeakMap(); - -type ClientProxyConfig = { - path: string[]; - isBelievedBad?: boolean; -}; - -function makeSdkProxy(obj: T, { path, isBelievedBad = false }: ClientProxyConfig): T { - let proxy: T = objToProxy.get(obj); - - if (!proxy) { - proxy = new Proxy(obj, { - get(target, prop, receiver) { - const propPath = [...path, String(prop)]; - const value = Reflect.get(target, prop, receiver); - - if (isBelievedBad || (!(prop in target) && value === undefined)) { - // If we're accessing a path that doesn't exist, it will probably eventually error. - // Let's proxy it and mark it bad so that we can control the error message. - // We proxy an empty class so that an invocation or construction attempt is possible. - return makeSdkProxy(class {}, { path: propPath, isBelievedBad: true }); - } - - if (value !== null && (typeof value === 'object' || typeof value === 'function')) { - return makeSdkProxy(value, { path: propPath, isBelievedBad }); - } - - return value; - }, - - apply(target, thisArg, args) { - if (isBelievedBad || typeof target !== 'function') { - const fullyQualifiedMethodName = path.join('.'); - const suggestions = getMethodSuggestions(fullyQualifiedMethodName); - throw new Error( - `${fullyQualifiedMethodName} is not a function. Did you mean: ${suggestions.join(', ')}`, - ); - } - - return Reflect.apply(target, proxyToObj.get(thisArg) ?? thisArg, args); - }, - - construct(target, args, newTarget) { - if (isBelievedBad || typeof target !== 'function') { - const fullyQualifiedMethodName = path.join('.'); - const suggestions = getMethodSuggestions(fullyQualifiedMethodName); - throw new Error( - `${fullyQualifiedMethodName} is not a constructor. Did you mean: ${suggestions.join(', ')}`, - ); - } - - return Reflect.construct(target, args, newTarget); - }, - }); - - objToProxy.set(obj, proxy); - proxyToObj.set(proxy, obj); - } - - return proxy; -} - -function parseError(code: string, error: unknown): string | undefined { - if (!(error instanceof Error)) return; - const message = error.name ? `${error.name}: ${error.message}` : error.message; - try { - // Deno uses V8; the first ":LINE:COLUMN" is the top of stack. - const lineNumber = error.stack?.match(/:([0-9]+):[0-9]+/)?.[1]; - // -1 for the zero-based indexing - const line = - lineNumber && - code - .split('\n') - .at(parseInt(lineNumber, 10) - 1) - ?.trim(); - return line ? `${message}\n at line ${lineNumber}\n ${line}` : message; - } catch { - return message; - } -} - -const fetch = async (req: Request): Promise => { - const { opts, code } = (await req.json()) as WorkerInput; - - const runFunctionSource = code ? getRunFunctionSource(code) : null; - if (!runFunctionSource) { - const message = - code ? - 'The code is missing a top-level `run` function.' - : 'The code argument is missing. Provide one containing a top-level `run` function.'; - return Response.json( - { - message: `${message} Write code within this template:\n\n\`\`\`\nasync function run(client) {\n // Fill this out\n}\n\`\`\``, - logLines: [], - errLines: [], - } satisfies WorkerError, - { status: 400, statusText: 'Code execution error' }, - ); - } - - const diagnostics = getTSDiagnostics(code); - if (diagnostics.length > 0) { - return Response.json( - { - message: `The code contains TypeScript diagnostics:\n${diagnostics.join('\n')}`, - logLines: [], - errLines: [], - } satisfies WorkerError, - { status: 400, statusText: 'Code execution error' }, - ); - } - - const client = new BeeperDesktop({ - ...opts, - }); - - const logLines: string[] = []; - const errLines: string[] = []; - const console = { - log: (...args: unknown[]) => { - logLines.push(util.format(...args)); - }, - error: (...args: unknown[]) => { - errLines.push(util.format(...args)); - }, - }; - try { - let run_ = async (client: any) => {}; - eval(`${code}\nrun_ = run;`); - const result = await run_(makeSdkProxy(client, { path: ['client'] })); - return Response.json({ - result, - logLines, - errLines, - } satisfies WorkerSuccess); - } catch (e) { - return Response.json( - { - message: parseError(code, e), - logLines, - errLines, - } satisfies WorkerError, - { status: 400, statusText: 'Code execution error' }, - ); - } -}; - -export default { fetch }; diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index 01307fb..227a8e1 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -1,14 +1,9 @@ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import path from 'node:path'; -import url from 'node:url'; -import BeeperDesktop, { ClientOptions } from '@beeper/desktop-api'; -import { ContentBlock, Endpoint, Metadata, ToolCallResult } from './tools/types'; - +import { Metadata, ToolCallResult, asTextContentResult } from './tools/types'; import { Tool } from '@modelcontextprotocol/sdk/types.js'; - -import { WorkerInput, WorkerError, WorkerSuccess } from './code-tool-types'; - +import { readEnv } from './server'; +import { WorkerSuccess } from './code-tool-types'; /** * A tool that runs code against a copy of the SDK. * @@ -18,156 +13,45 @@ import { WorkerInput, WorkerError, WorkerSuccess } from './code-tool-types'; * * @param endpoints - The endpoints to include in the list. */ -export async function codeTool(): Promise { +export async function codeTool() { const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] }; const tool: Tool = { name: 'execute', description: - 'Runs JavaScript code to interact with the API.\n\nYou are a skilled programmer writing code to interface with the service.\nDefine an async function named "run" that takes a single parameter of an initialized client named "client", and it will be run.\nWrite code within this template:\n\n```\nasync function run(client) {\n // Fill this out\n}\n```\n\nYou will be returned anything that your function returns, plus the results of any console.log statements.\nIf any code triggers an error, the tool will return an error response, so you do not need to add error handling unless you want to output something more helpful than the raw error.\nIt is not necessary to add comments to code, unless by adding those comments you believe that you can generate better code.\nThis code will run in a container, and you will not be able to use fetch or otherwise interact with the network calls other than through the client you are given.\nAny variables you define won\'t live between successive uses of this call, so make sure to return or log any data you might need later.', + 'Runs JavaScript code to interact with the API.\n\nYou are a skilled programmer writing code to interface with the service.\nDefine an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.\nWrite code within this template:\n\n```\nasync function run(client) {\n // Fill this out\n}\n```\n\nYou will be returned anything that your function returns, plus the results of any console.log statements.\nIf any code triggers an error, the tool will return an error response, so you do not need to add error handling unless you want to output something more helpful than the raw error.\nIt is not necessary to add comments to code, unless by adding those comments you believe that you can generate better code.\nThis code will run in a container, and you will not be able to use fetch or otherwise interact with the network calls other than through the client you are given.\nAny variables you define won\'t live between successive uses of this call, so make sure to return or log any data you might need later.', inputSchema: { type: 'object', properties: { code: { type: 'string' } } }, }; - - // Import dynamically to avoid failing at import time in cases where the environment is not well-supported. - const { newDenoHTTPWorker } = await import('@valtown/deno-http-worker'); - const { workerPath } = await import('./code-tool-paths.cjs'); - - const handler = async (client: BeeperDesktop, args: unknown): Promise => { - const baseURLHostname = new URL(client.baseURL).hostname; - const { code } = args as { code: string }; - - const allowRead = [ - 'code-tool-worker.mjs', - `${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`, - path.resolve(path.dirname(workerPath), '..'), - ].join(','); - - const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), { - runFlags: [ - `--node-modules-dir=manual`, - `--allow-read=${allowRead}`, - `--allow-net=${baseURLHostname}`, - // Allow environment variables because instantiating the client will try to read from them, - // even though they are not set. - '--allow-env', - ], - printOutput: true, - spawnOptions: { - cwd: path.dirname(workerPath), + const handler = async (_: unknown, args: any): Promise => { + const code = args.code as string; + + // this is not required, but passing a Stainless API key for the matching project_name + // will allow you to run code-mode queries against non-published versions of your SDK. + const stainlessAPIKey = readEnv('STAINLESS_API_KEY'); + const codeModeEndpoint = + readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool/'; + + const res = await fetch(codeModeEndpoint, { + method: 'POST', + headers: { + ...(stainlessAPIKey && { Authorization: stainlessAPIKey }), + 'Content-Type': 'application/json', + client_envs: JSON.stringify({ BEEPER_ACCESS_TOKEN: readEnv('BEEPER_ACCESS_TOKEN') }), }, + body: JSON.stringify({ + project_name: 'beeper-desktop-api', + code, + }), }); - try { - const resp = await new Promise((resolve, reject) => { - worker.addEventListener('exit', (exitCode) => { - reject(new Error(`Worker exited with code ${exitCode}`)); - }); - - const opts: ClientOptions = { - baseURL: client.baseURL, - accessToken: client.accessToken, - defaultHeaders: { - 'X-Stainless-MCP': 'true', - }, - }; - - const req = worker.request( - 'http://localhost', - { - headers: { - 'content-type': 'application/json', - }, - method: 'POST', - }, - (resp) => { - const body: Uint8Array[] = []; - resp.on('error', (err) => { - reject(err); - }); - resp.on('data', (chunk) => { - body.push(chunk); - }); - resp.on('end', () => { - resolve( - new Response(Buffer.concat(body).toString(), { - status: resp.statusCode ?? 200, - headers: resp.headers as any, - }), - ); - }); - }, - ); - - const body = JSON.stringify({ - opts, - code, - } satisfies WorkerInput); - - req.write(body, (err) => { - if (err != null) { - reject(err); - } - }); - - req.end(); - }); - - if (resp.status === 200) { - const { result, logLines, errLines } = (await resp.json()) as WorkerSuccess; - const returnOutput: ContentBlock | null = - result == null ? null : ( - { - type: 'text', - text: typeof result === 'string' ? result : JSON.stringify(result), - } - ); - const logOutput: ContentBlock | null = - logLines.length === 0 ? - null - : { - type: 'text', - text: logLines.join('\n'), - }; - const errOutput: ContentBlock | null = - errLines.length === 0 ? - null - : { - type: 'text', - text: 'Error output:\n' + errLines.join('\n'), - }; - return { - content: [returnOutput, logOutput, errOutput].filter((block) => block !== null), - }; - } else { - const { message, logLines, errLines } = (await resp.json()) as WorkerError; - const messageOutput: ContentBlock | null = - message == null ? null : ( - { - type: 'text', - text: message, - } - ); - const logOutput: ContentBlock | null = - logLines.length === 0 ? - null - : { - type: 'text', - text: logLines.join('\n'), - }; - const errOutput: ContentBlock | null = - errLines.length === 0 ? - null - : { - type: 'text', - text: 'Error output:\n' + errLines.join('\n'), - }; - return { - content: [messageOutput, logOutput, errOutput].filter((block) => block !== null), - isError: true, - }; - } - } finally { - worker.terminate(); + if (!res.ok) { + throw new Error( + `${res.status}: ${ + res.statusText + } error when trying to contact Code Tool server. Details: ${await res.text()}`, + ); } + + return asTextContentResult((await res.json()) as WorkerSuccess); }; return { metadata, tool, handler }; diff --git a/packages/mcp-server/src/docs-search-tool.ts b/packages/mcp-server/src/docs-search-tool.ts index 917f2c1..f80b5e4 100644 --- a/packages/mcp-server/src/docs-search-tool.ts +++ b/packages/mcp-server/src/docs-search-tool.ts @@ -46,6 +46,13 @@ export const handler = async (_: unknown, args: Record | undefi const body = args as any; const query = new URLSearchParams(body).toString(); const result = await fetch(`${docsSearchURL}?${query}`); + + if (!result.ok) { + throw new Error( + `${result.status}: ${result.statusText} when using doc search tool. Details: ${await result.text()}`, + ); + } + return asTextContentResult(await result.json()); }; From 267080003620b463563fbe0fa1808a12d471a692 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 6 Dec 2025 03:39:09 +0000 Subject: [PATCH 12/16] fix(mcp): return correct lines on typescript errors --- .devcontainer/Dockerfile | 23 ++ .eslintrc.js | 10 + jest.setup.ts | 0 packages/mcp-server/src/did-you-mean-proxy.ts | 356 ++++++++++++++++++ src/internal/polyfill/file.node.d.ts | 14 + src/internal/polyfill/file.node.mjs | 9 + tests/responses.test.ts | 24 ++ 7 files changed, 436 insertions(+) create mode 100644 .devcontainer/Dockerfile create mode 100644 .eslintrc.js create mode 100644 jest.setup.ts create mode 100644 packages/mcp-server/src/did-you-mean-proxy.ts create mode 100644 src/internal/polyfill/file.node.d.ts create mode 100644 src/internal/polyfill/file.node.mjs create mode 100644 tests/responses.test.ts diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..8ea34be --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,23 @@ +# syntax=docker/dockerfile:1 +FROM debian:bookworm-slim AS stainless + +RUN apt-get update && apt-get install -y \ + nodejs \ + npm \ + yarnpkg \ + && apt-get clean autoclean + +# Ensure UTF-8 encoding +ENV LANG=C.UTF-8 +ENV LC_ALL=C.UTF-8 + +# Yarn +RUN ln -sf /usr/bin/yarnpkg /usr/bin/yarn + +WORKDIR /workspace + +COPY package.json yarn.lock /workspace/ + +RUN yarn install + +COPY . /workspace diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..60f0e7a --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,10 @@ +module.exports = { + parser: '@typescript-eslint/parser', + plugins: ['@typescript-eslint', 'unused-imports', 'prettier'], + rules: { + 'no-unused-vars': 'off', + 'prettier/prettier': 'error', + 'unused-imports/no-unused-imports': 'error', + }, + root: true, +}; diff --git a/jest.setup.ts b/jest.setup.ts new file mode 100644 index 0000000..e69de29 diff --git a/packages/mcp-server/src/did-you-mean-proxy.ts b/packages/mcp-server/src/did-you-mean-proxy.ts new file mode 100644 index 0000000..8c1380d --- /dev/null +++ b/packages/mcp-server/src/did-you-mean-proxy.ts @@ -0,0 +1,356 @@ +import Fuse from 'fuse.js'; + +const allKinds = ['string', 'number', 'boolean', 'object', 'array', 'method', 'constructor'] as const; +type Kind = (typeof allKinds)[number]; + +const nodeInspect = Symbol.for('nodejs.util.inspect.custom'); +const denoInspect = Symbol.for('Deno.customInspect'); + +const stringMethods = new Set(Reflect.ownKeys(String.prototype).filter((k) => typeof k === 'string')); +const numberMethods = new Set(Reflect.ownKeys(Number.prototype).filter((k) => typeof k === 'string')); +const arrayMethods = new Set(Reflect.ownKeys(Array.prototype).filter((k) => typeof k === 'string')); + +function getApplyKinds(name?: string | symbol): readonly Kind[] { + if (!name || name === nodeInspect || name === denoInspect) { + return allKinds; + } + + if (name === Symbol.toPrimitive || name === 'toString' || name === 'valueOf') { + return ['string', 'number', 'boolean']; + } + + if (name === Symbol.iterator) { + return ['array']; + } + + if (typeof name !== 'string') { + return ['method']; + } + + const kinds: Kind[] = []; + if (stringMethods.has(name)) { + kinds.push('string'); + } else if (numberMethods.has(name)) { + kinds.push('number'); + } else if (arrayMethods.has(name)) { + kinds.push('array'); + } + + return kinds.length > 0 ? kinds : ['method']; +} + +type KindPaths = Record; + +function traverseKinds( + obj: object, + path: string = '', + result: KindPaths = { + string: [], + number: [], + boolean: [], + object: [], + array: [], + method: [], + constructor: [], + }, +): KindPaths { + while (obj !== null) { + for (const key of Reflect.ownKeys(obj)) { + if (typeof key !== 'string') { + continue; + } + + if (key === 'constructor') { + continue; + } + + if (!/^[a-zA-Z]/.test(key)) { + continue; + } + + const value = Reflect.get(obj, key); + let kind: Kind; + + switch (typeof value) { + case 'string': { + kind = 'string'; + break; + } + case 'number': + case 'bigint': { + kind = 'number'; + break; + } + case 'boolean': { + kind = 'boolean'; + break; + } + case 'object': { + if (value === null) { + continue; + } + kind = Array.isArray(value) ? 'array' : 'object'; + break; + } + case 'function': { + kind = + key === value.name && value.name === value.prototype?.constructor?.name ? + 'constructor' + : 'method'; + break; + } + default: { + continue; + } + } + + const fullKey = path ? `${path}.${key}` : key; + result[kind].push(fullKey); + + if (kind === 'object') { + traverseKinds(value, fullKey, result); + } else if (kind === 'array' && value.length > 0) { + traverseKinds(value[0], `${fullKey}[]`, result); + } + } + + obj = Object.getPrototypeOf(obj); + if (obj === Object.prototype || obj === Array.prototype) { + break; + } + } + + return result; +} + +export type MakeError = (props: { + expected: readonly Kind[]; + rootPath: (string | symbol)[]; + path: (string | symbol)[]; + suggestions: { item: string; score: number }[]; +}) => string; + +export type ProxyConfig = { + /** + * Whether to also proxy the return values. They will be proxied with + * the same config, except the root path will be blank. Defaults to true. + */ + proxyReturn?: boolean; + /** + * The path to the root object, prepended to path suggestions. For example, + * if this is set to ['client'], then suggestions will be 'client.repos.list', + * 'client.users.list', etc. + */ + rootPath?: (string | symbol)[]; + /** + * Customize the error message to be thrown. The root path will not be + * prepended to either the path or the suggestions. + */ + makeSuggestionError?: MakeError; +}; + +function shouldProxy(value: unknown): value is NonNullable { + return value !== null && (typeof value === 'object' || typeof value === 'function'); +} + +const emptyTargetSymbol = Symbol.for('did-you-mean-proxy.emptyTargetPath'); + +type EmptyTarget = { + [emptyTargetSymbol]: { + getError: () => string; + }; +}; +type EmptyTargetInfo = EmptyTarget[typeof emptyTargetSymbol]; + +/** + * We use a special empty target so we can catch calls and constructions. + * Also useful for de-proxying in the end; if we get an empty target, we know + * we can throw an error. + */ +function createEmptyTarget(info: EmptyTargetInfo): EmptyTarget { + const emptyTarget = function () {} as any; + emptyTarget[nodeInspect] = () => { + throw info.getError(); + }; + emptyTarget[denoInspect] = () => { + throw info.getError(); + }; + emptyTarget[emptyTargetSymbol] = info; + return emptyTarget; +} + +function isEmptyTarget(value: unknown): value is EmptyTarget { + return typeof value === 'function' && (value as any)[emptyTargetSymbol] !== undefined; +} + +export const defaultMakeError: MakeError = function ({ expected, rootPath, path, suggestions }) { + const rootPathString = + rootPath.length > 0 ? `${rootPath.filter((p) => typeof p === 'string').join('.')}.` : ''; + const pathString = `'${rootPathString}${path.filter((p) => typeof p === 'string').join('.')}'`; + + let header = `${pathString} does not exist.`; + if (expected.length === 1) { + const expectedType = + expected[0] === 'array' ? 'an array' + : expected[0] === 'object' ? 'an object' + : expected[0] === 'method' ? 'a function' + : `a ${expected[0]}`; + header = `${pathString} is not ${expectedType}.`; + } + + const suggestionStrings = suggestions + // TODO(sometime): thresholding? + .filter((suggestion) => suggestion.score < 1) + .slice(0, 5) + .map((suggestion) => `'${rootPathString}${suggestion.item}'`); + + let body = ''; + if (suggestionStrings.length === 1) { + body = `Did you mean ${suggestionStrings[0]}?`; + } else if (suggestionStrings.length > 1) { + const commas = suggestionStrings.slice(0, suggestionStrings.length - 1).join(', '); + body = `Did you mean ${commas}, or ${suggestionStrings[suggestionStrings.length - 1]}?`; + } + + return body ? `${header} ${body}` : header; +}; + +export const debugMakeError: MakeError = function ({ expected, path, suggestions }) { + return `path ${path.filter((p) => typeof p === 'string').join('.')}; expected ${expected.join(', ')} +${suggestions + .slice(0, 10) + .map((suggestion) => ` - [${suggestion.score.toFixed(2)}] ${suggestion.item}`) + .join('\n')} +`; +}; + +const proxyToObj = new WeakMap(); + +export function makeProxy(root: Root, config: ProxyConfig = {}): Root { + let kindPaths: KindPaths | null = null; + + config.proxyReturn ??= true; + config.rootPath ??= ['']; + config.makeSuggestionError ??= defaultMakeError; + + const { proxyReturn, rootPath, makeSuggestionError } = config; + const { rootPath: _, ...subconfig } = config; + + function makeError(pathWithRoot: (string | symbol)[], expected: readonly Kind[]) { + if (!kindPaths) { + kindPaths = traverseKinds(root); + } + + const fuse = new Fuse( + expected.flatMap((kind) => kindPaths![kind]), + { includeScore: true }, + ); + + const path = pathWithRoot.slice(rootPath.length); + const searchKey: string[] = []; + for (const key of path) { + // Convert array keys to []: + if (/^\d+$/.test(key.toString())) { + searchKey.push('[]'); + } else if (typeof key === 'string') { + searchKey.push('.'); + searchKey.push(key); + } + } + + const key = searchKey.join(''); + const suggestions = fuse.search(key.slice(1)) as { item: string; score: number }[]; + + return makeSuggestionError({ expected, rootPath, path, suggestions }); + } + + function subproxy(obj: T, path: (string | symbol)[]): T { + const handlers: ProxyHandler = { + get(target, prop, receiver) { + const newPath = [...path, prop]; + const value = Reflect.get(target, prop, receiver); + + if (value === undefined && !Reflect.has(target, prop)) { + // Some common special cases: + // - 'then' is called on a non-thenable. + // - 'toJSON' is called when it's not defined. + // In these cases, we actually want to return undefined, so we + // resolve to the top-level thing. + if (prop === 'then' || prop === 'toJSON') { + return undefined; + } + + return subproxy( + createEmptyTarget({ + getError: () => makeError(newPath, allKinds), + }), + newPath, + ); + } + + return shouldProxy(value) ? subproxy(value, newPath) : value; + }, + construct(target, args, newTarget) { + if (isEmptyTarget(target) || typeof target !== 'function') { + throw new Error(makeError(path, ['constructor'])); + } + + const result = Reflect.construct(target, args, newTarget); + + return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; + }, + apply(target, thisArg, args) { + if (isEmptyTarget(target) || typeof target !== 'function') { + throw new Error(makeError(path, getApplyKinds(path[path.length - 1]))); + } + + const correctThisArg = proxyToObj.get(thisArg) ?? thisArg; + const proxiedArgs = + proxyReturn ? args.map((arg) => (shouldProxy(arg) ? makeProxy(arg, subconfig) : arg)) : args; + const result = Reflect.apply(target, correctThisArg, proxiedArgs); + + return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; + }, + }; + + // All other traps demand a non-empty target: + for (const trap of [ + 'defineProperty', + 'has', + 'set', + 'deleteProperty', + 'ownKeys', + 'getPrototypeOf', + 'setPrototypeOf', + 'isExtensible', + 'preventExtensions', + 'getOwnPropertyDescriptor', + ] as const) { + handlers[trap] = function (target: any, ...args: any[]) { + if (isEmptyTarget(target)) { + throw new Error(makeError(path, allKinds)); + } + + return (Reflect[trap] as any)(target, ...args); + }; + } + + const proxy = new Proxy(obj, handlers); + proxyToObj.set(proxy, obj); + + return proxy; + } + + return subproxy(root, rootPath); +} + +export function deproxy(value: T): T { + // Primitives never get proxied, so these are safe: + if (typeof value !== 'object' && typeof value !== 'function') { + return value; + } + if (isEmptyTarget(value)) { + throw new Error(value[emptyTargetSymbol].getError()); + } + return proxyToObj.get(value) ?? value; +} diff --git a/src/internal/polyfill/file.node.d.ts b/src/internal/polyfill/file.node.d.ts new file mode 100644 index 0000000..c95276d --- /dev/null +++ b/src/internal/polyfill/file.node.d.ts @@ -0,0 +1,14 @@ +/** + * This file polyfills the global `File` object for you if it's not already defined + * when running on Node.js + * + * This is only needed on Node.js v18 & v19. Newer versions already define `File` + * as a global. + */ + +// @ts-ignore +type nodeBuffer = typeof import('node:buffer'); +declare const File: typeof globalThis extends { File: unknown } ? (typeof globalThis)['File'] +: nodeBuffer extends { File: unknown } ? nodeBuffer['File'] +: any; +export {}; diff --git a/src/internal/polyfill/file.node.mjs b/src/internal/polyfill/file.node.mjs new file mode 100644 index 0000000..520dcb8 --- /dev/null +++ b/src/internal/polyfill/file.node.mjs @@ -0,0 +1,9 @@ +/** + * This file polyfills the global `File` object for you if it's not already defined + * when running on Node.js + * + * This is only needed on Node.js v18 & v19. Newer versions already define `File` + * as a global. + */ + +import './file.node.js'; diff --git a/tests/responses.test.ts b/tests/responses.test.ts new file mode 100644 index 0000000..2259dc0 --- /dev/null +++ b/tests/responses.test.ts @@ -0,0 +1,24 @@ +import { createResponseHeaders } from '@beeper/desktop-api/internal/headers'; + +describe('response parsing', () => { + // TODO: test unicode characters + test('headers are case agnostic', async () => { + const headers = createResponseHeaders(new Headers({ 'Content-Type': 'foo', Accept: 'text/plain' })); + expect(headers['content-type']).toEqual('foo'); + expect(headers['Content-type']).toEqual('foo'); + expect(headers['Content-Type']).toEqual('foo'); + expect(headers['accept']).toEqual('text/plain'); + expect(headers['Accept']).toEqual('text/plain'); + expect(headers['Hello-World']).toBeUndefined(); + }); + + test('duplicate headers are concatenated', () => { + const headers = createResponseHeaders( + new Headers([ + ['Content-Type', 'text/xml'], + ['Content-Type', 'application/json'], + ]), + ); + expect(headers['content-type']).toBe('text/xml, application/json'); + }); +}); From 61481002797da513cdf64b33161fb6399de710aa Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 6 Dec 2025 03:39:40 +0000 Subject: [PATCH 13/16] chore(internal): codegen related update --- .devcontainer/Dockerfile | 23 -- .eslintrc.js | 10 - jest.setup.ts | 0 packages/mcp-server/src/did-you-mean-proxy.ts | 356 ------------------ src/internal/polyfill/file.node.d.ts | 14 - src/internal/polyfill/file.node.mjs | 9 - tests/responses.test.ts | 24 -- 7 files changed, 436 deletions(-) delete mode 100644 .devcontainer/Dockerfile delete mode 100644 .eslintrc.js delete mode 100644 jest.setup.ts delete mode 100644 packages/mcp-server/src/did-you-mean-proxy.ts delete mode 100644 src/internal/polyfill/file.node.d.ts delete mode 100644 src/internal/polyfill/file.node.mjs delete mode 100644 tests/responses.test.ts diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile deleted file mode 100644 index 8ea34be..0000000 --- a/.devcontainer/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -# syntax=docker/dockerfile:1 -FROM debian:bookworm-slim AS stainless - -RUN apt-get update && apt-get install -y \ - nodejs \ - npm \ - yarnpkg \ - && apt-get clean autoclean - -# Ensure UTF-8 encoding -ENV LANG=C.UTF-8 -ENV LC_ALL=C.UTF-8 - -# Yarn -RUN ln -sf /usr/bin/yarnpkg /usr/bin/yarn - -WORKDIR /workspace - -COPY package.json yarn.lock /workspace/ - -RUN yarn install - -COPY . /workspace diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 60f0e7a..0000000 --- a/.eslintrc.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint', 'unused-imports', 'prettier'], - rules: { - 'no-unused-vars': 'off', - 'prettier/prettier': 'error', - 'unused-imports/no-unused-imports': 'error', - }, - root: true, -}; diff --git a/jest.setup.ts b/jest.setup.ts deleted file mode 100644 index e69de29..0000000 diff --git a/packages/mcp-server/src/did-you-mean-proxy.ts b/packages/mcp-server/src/did-you-mean-proxy.ts deleted file mode 100644 index 8c1380d..0000000 --- a/packages/mcp-server/src/did-you-mean-proxy.ts +++ /dev/null @@ -1,356 +0,0 @@ -import Fuse from 'fuse.js'; - -const allKinds = ['string', 'number', 'boolean', 'object', 'array', 'method', 'constructor'] as const; -type Kind = (typeof allKinds)[number]; - -const nodeInspect = Symbol.for('nodejs.util.inspect.custom'); -const denoInspect = Symbol.for('Deno.customInspect'); - -const stringMethods = new Set(Reflect.ownKeys(String.prototype).filter((k) => typeof k === 'string')); -const numberMethods = new Set(Reflect.ownKeys(Number.prototype).filter((k) => typeof k === 'string')); -const arrayMethods = new Set(Reflect.ownKeys(Array.prototype).filter((k) => typeof k === 'string')); - -function getApplyKinds(name?: string | symbol): readonly Kind[] { - if (!name || name === nodeInspect || name === denoInspect) { - return allKinds; - } - - if (name === Symbol.toPrimitive || name === 'toString' || name === 'valueOf') { - return ['string', 'number', 'boolean']; - } - - if (name === Symbol.iterator) { - return ['array']; - } - - if (typeof name !== 'string') { - return ['method']; - } - - const kinds: Kind[] = []; - if (stringMethods.has(name)) { - kinds.push('string'); - } else if (numberMethods.has(name)) { - kinds.push('number'); - } else if (arrayMethods.has(name)) { - kinds.push('array'); - } - - return kinds.length > 0 ? kinds : ['method']; -} - -type KindPaths = Record; - -function traverseKinds( - obj: object, - path: string = '', - result: KindPaths = { - string: [], - number: [], - boolean: [], - object: [], - array: [], - method: [], - constructor: [], - }, -): KindPaths { - while (obj !== null) { - for (const key of Reflect.ownKeys(obj)) { - if (typeof key !== 'string') { - continue; - } - - if (key === 'constructor') { - continue; - } - - if (!/^[a-zA-Z]/.test(key)) { - continue; - } - - const value = Reflect.get(obj, key); - let kind: Kind; - - switch (typeof value) { - case 'string': { - kind = 'string'; - break; - } - case 'number': - case 'bigint': { - kind = 'number'; - break; - } - case 'boolean': { - kind = 'boolean'; - break; - } - case 'object': { - if (value === null) { - continue; - } - kind = Array.isArray(value) ? 'array' : 'object'; - break; - } - case 'function': { - kind = - key === value.name && value.name === value.prototype?.constructor?.name ? - 'constructor' - : 'method'; - break; - } - default: { - continue; - } - } - - const fullKey = path ? `${path}.${key}` : key; - result[kind].push(fullKey); - - if (kind === 'object') { - traverseKinds(value, fullKey, result); - } else if (kind === 'array' && value.length > 0) { - traverseKinds(value[0], `${fullKey}[]`, result); - } - } - - obj = Object.getPrototypeOf(obj); - if (obj === Object.prototype || obj === Array.prototype) { - break; - } - } - - return result; -} - -export type MakeError = (props: { - expected: readonly Kind[]; - rootPath: (string | symbol)[]; - path: (string | symbol)[]; - suggestions: { item: string; score: number }[]; -}) => string; - -export type ProxyConfig = { - /** - * Whether to also proxy the return values. They will be proxied with - * the same config, except the root path will be blank. Defaults to true. - */ - proxyReturn?: boolean; - /** - * The path to the root object, prepended to path suggestions. For example, - * if this is set to ['client'], then suggestions will be 'client.repos.list', - * 'client.users.list', etc. - */ - rootPath?: (string | symbol)[]; - /** - * Customize the error message to be thrown. The root path will not be - * prepended to either the path or the suggestions. - */ - makeSuggestionError?: MakeError; -}; - -function shouldProxy(value: unknown): value is NonNullable { - return value !== null && (typeof value === 'object' || typeof value === 'function'); -} - -const emptyTargetSymbol = Symbol.for('did-you-mean-proxy.emptyTargetPath'); - -type EmptyTarget = { - [emptyTargetSymbol]: { - getError: () => string; - }; -}; -type EmptyTargetInfo = EmptyTarget[typeof emptyTargetSymbol]; - -/** - * We use a special empty target so we can catch calls and constructions. - * Also useful for de-proxying in the end; if we get an empty target, we know - * we can throw an error. - */ -function createEmptyTarget(info: EmptyTargetInfo): EmptyTarget { - const emptyTarget = function () {} as any; - emptyTarget[nodeInspect] = () => { - throw info.getError(); - }; - emptyTarget[denoInspect] = () => { - throw info.getError(); - }; - emptyTarget[emptyTargetSymbol] = info; - return emptyTarget; -} - -function isEmptyTarget(value: unknown): value is EmptyTarget { - return typeof value === 'function' && (value as any)[emptyTargetSymbol] !== undefined; -} - -export const defaultMakeError: MakeError = function ({ expected, rootPath, path, suggestions }) { - const rootPathString = - rootPath.length > 0 ? `${rootPath.filter((p) => typeof p === 'string').join('.')}.` : ''; - const pathString = `'${rootPathString}${path.filter((p) => typeof p === 'string').join('.')}'`; - - let header = `${pathString} does not exist.`; - if (expected.length === 1) { - const expectedType = - expected[0] === 'array' ? 'an array' - : expected[0] === 'object' ? 'an object' - : expected[0] === 'method' ? 'a function' - : `a ${expected[0]}`; - header = `${pathString} is not ${expectedType}.`; - } - - const suggestionStrings = suggestions - // TODO(sometime): thresholding? - .filter((suggestion) => suggestion.score < 1) - .slice(0, 5) - .map((suggestion) => `'${rootPathString}${suggestion.item}'`); - - let body = ''; - if (suggestionStrings.length === 1) { - body = `Did you mean ${suggestionStrings[0]}?`; - } else if (suggestionStrings.length > 1) { - const commas = suggestionStrings.slice(0, suggestionStrings.length - 1).join(', '); - body = `Did you mean ${commas}, or ${suggestionStrings[suggestionStrings.length - 1]}?`; - } - - return body ? `${header} ${body}` : header; -}; - -export const debugMakeError: MakeError = function ({ expected, path, suggestions }) { - return `path ${path.filter((p) => typeof p === 'string').join('.')}; expected ${expected.join(', ')} -${suggestions - .slice(0, 10) - .map((suggestion) => ` - [${suggestion.score.toFixed(2)}] ${suggestion.item}`) - .join('\n')} -`; -}; - -const proxyToObj = new WeakMap(); - -export function makeProxy(root: Root, config: ProxyConfig = {}): Root { - let kindPaths: KindPaths | null = null; - - config.proxyReturn ??= true; - config.rootPath ??= ['']; - config.makeSuggestionError ??= defaultMakeError; - - const { proxyReturn, rootPath, makeSuggestionError } = config; - const { rootPath: _, ...subconfig } = config; - - function makeError(pathWithRoot: (string | symbol)[], expected: readonly Kind[]) { - if (!kindPaths) { - kindPaths = traverseKinds(root); - } - - const fuse = new Fuse( - expected.flatMap((kind) => kindPaths![kind]), - { includeScore: true }, - ); - - const path = pathWithRoot.slice(rootPath.length); - const searchKey: string[] = []; - for (const key of path) { - // Convert array keys to []: - if (/^\d+$/.test(key.toString())) { - searchKey.push('[]'); - } else if (typeof key === 'string') { - searchKey.push('.'); - searchKey.push(key); - } - } - - const key = searchKey.join(''); - const suggestions = fuse.search(key.slice(1)) as { item: string; score: number }[]; - - return makeSuggestionError({ expected, rootPath, path, suggestions }); - } - - function subproxy(obj: T, path: (string | symbol)[]): T { - const handlers: ProxyHandler = { - get(target, prop, receiver) { - const newPath = [...path, prop]; - const value = Reflect.get(target, prop, receiver); - - if (value === undefined && !Reflect.has(target, prop)) { - // Some common special cases: - // - 'then' is called on a non-thenable. - // - 'toJSON' is called when it's not defined. - // In these cases, we actually want to return undefined, so we - // resolve to the top-level thing. - if (prop === 'then' || prop === 'toJSON') { - return undefined; - } - - return subproxy( - createEmptyTarget({ - getError: () => makeError(newPath, allKinds), - }), - newPath, - ); - } - - return shouldProxy(value) ? subproxy(value, newPath) : value; - }, - construct(target, args, newTarget) { - if (isEmptyTarget(target) || typeof target !== 'function') { - throw new Error(makeError(path, ['constructor'])); - } - - const result = Reflect.construct(target, args, newTarget); - - return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; - }, - apply(target, thisArg, args) { - if (isEmptyTarget(target) || typeof target !== 'function') { - throw new Error(makeError(path, getApplyKinds(path[path.length - 1]))); - } - - const correctThisArg = proxyToObj.get(thisArg) ?? thisArg; - const proxiedArgs = - proxyReturn ? args.map((arg) => (shouldProxy(arg) ? makeProxy(arg, subconfig) : arg)) : args; - const result = Reflect.apply(target, correctThisArg, proxiedArgs); - - return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; - }, - }; - - // All other traps demand a non-empty target: - for (const trap of [ - 'defineProperty', - 'has', - 'set', - 'deleteProperty', - 'ownKeys', - 'getPrototypeOf', - 'setPrototypeOf', - 'isExtensible', - 'preventExtensions', - 'getOwnPropertyDescriptor', - ] as const) { - handlers[trap] = function (target: any, ...args: any[]) { - if (isEmptyTarget(target)) { - throw new Error(makeError(path, allKinds)); - } - - return (Reflect[trap] as any)(target, ...args); - }; - } - - const proxy = new Proxy(obj, handlers); - proxyToObj.set(proxy, obj); - - return proxy; - } - - return subproxy(root, rootPath); -} - -export function deproxy(value: T): T { - // Primitives never get proxied, so these are safe: - if (typeof value !== 'object' && typeof value !== 'function') { - return value; - } - if (isEmptyTarget(value)) { - throw new Error(value[emptyTargetSymbol].getError()); - } - return proxyToObj.get(value) ?? value; -} diff --git a/src/internal/polyfill/file.node.d.ts b/src/internal/polyfill/file.node.d.ts deleted file mode 100644 index c95276d..0000000 --- a/src/internal/polyfill/file.node.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file polyfills the global `File` object for you if it's not already defined - * when running on Node.js - * - * This is only needed on Node.js v18 & v19. Newer versions already define `File` - * as a global. - */ - -// @ts-ignore -type nodeBuffer = typeof import('node:buffer'); -declare const File: typeof globalThis extends { File: unknown } ? (typeof globalThis)['File'] -: nodeBuffer extends { File: unknown } ? nodeBuffer['File'] -: any; -export {}; diff --git a/src/internal/polyfill/file.node.mjs b/src/internal/polyfill/file.node.mjs deleted file mode 100644 index 520dcb8..0000000 --- a/src/internal/polyfill/file.node.mjs +++ /dev/null @@ -1,9 +0,0 @@ -/** - * This file polyfills the global `File` object for you if it's not already defined - * when running on Node.js - * - * This is only needed on Node.js v18 & v19. Newer versions already define `File` - * as a global. - */ - -import './file.node.js'; diff --git a/tests/responses.test.ts b/tests/responses.test.ts deleted file mode 100644 index 2259dc0..0000000 --- a/tests/responses.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createResponseHeaders } from '@beeper/desktop-api/internal/headers'; - -describe('response parsing', () => { - // TODO: test unicode characters - test('headers are case agnostic', async () => { - const headers = createResponseHeaders(new Headers({ 'Content-Type': 'foo', Accept: 'text/plain' })); - expect(headers['content-type']).toEqual('foo'); - expect(headers['Content-type']).toEqual('foo'); - expect(headers['Content-Type']).toEqual('foo'); - expect(headers['accept']).toEqual('text/plain'); - expect(headers['Accept']).toEqual('text/plain'); - expect(headers['Hello-World']).toBeUndefined(); - }); - - test('duplicate headers are concatenated', () => { - const headers = createResponseHeaders( - new Headers([ - ['Content-Type', 'text/xml'], - ['Content-Type', 'application/json'], - ]), - ); - expect(headers['content-type']).toBe('text/xml, application/json'); - }); -}); From e4d8fd374547a678ae125358bcbc52f092df00cb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 6 Dec 2025 03:40:26 +0000 Subject: [PATCH 14/16] fix(mcp): correct code tool API endpoint --- .devcontainer/Dockerfile | 23 ++ .eslintrc.js | 10 + jest.setup.ts | 0 packages/mcp-server/src/code-tool.ts | 2 +- packages/mcp-server/src/did-you-mean-proxy.ts | 356 ++++++++++++++++++ src/internal/polyfill/file.node.d.ts | 14 + src/internal/polyfill/file.node.mjs | 9 + tests/responses.test.ts | 24 ++ 8 files changed, 437 insertions(+), 1 deletion(-) create mode 100644 .devcontainer/Dockerfile create mode 100644 .eslintrc.js create mode 100644 jest.setup.ts create mode 100644 packages/mcp-server/src/did-you-mean-proxy.ts create mode 100644 src/internal/polyfill/file.node.d.ts create mode 100644 src/internal/polyfill/file.node.mjs create mode 100644 tests/responses.test.ts diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000..8ea34be --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,23 @@ +# syntax=docker/dockerfile:1 +FROM debian:bookworm-slim AS stainless + +RUN apt-get update && apt-get install -y \ + nodejs \ + npm \ + yarnpkg \ + && apt-get clean autoclean + +# Ensure UTF-8 encoding +ENV LANG=C.UTF-8 +ENV LC_ALL=C.UTF-8 + +# Yarn +RUN ln -sf /usr/bin/yarnpkg /usr/bin/yarn + +WORKDIR /workspace + +COPY package.json yarn.lock /workspace/ + +RUN yarn install + +COPY . /workspace diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..60f0e7a --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,10 @@ +module.exports = { + parser: '@typescript-eslint/parser', + plugins: ['@typescript-eslint', 'unused-imports', 'prettier'], + rules: { + 'no-unused-vars': 'off', + 'prettier/prettier': 'error', + 'unused-imports/no-unused-imports': 'error', + }, + root: true, +}; diff --git a/jest.setup.ts b/jest.setup.ts new file mode 100644 index 0000000..e69de29 diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index 227a8e1..ed4b0c1 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -28,7 +28,7 @@ export async function codeTool() { // will allow you to run code-mode queries against non-published versions of your SDK. const stainlessAPIKey = readEnv('STAINLESS_API_KEY'); const codeModeEndpoint = - readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool/'; + readEnv('CODE_MODE_ENDPOINT_URL') ?? 'https://api.stainless.com/api/ai/code-tool'; const res = await fetch(codeModeEndpoint, { method: 'POST', diff --git a/packages/mcp-server/src/did-you-mean-proxy.ts b/packages/mcp-server/src/did-you-mean-proxy.ts new file mode 100644 index 0000000..8c1380d --- /dev/null +++ b/packages/mcp-server/src/did-you-mean-proxy.ts @@ -0,0 +1,356 @@ +import Fuse from 'fuse.js'; + +const allKinds = ['string', 'number', 'boolean', 'object', 'array', 'method', 'constructor'] as const; +type Kind = (typeof allKinds)[number]; + +const nodeInspect = Symbol.for('nodejs.util.inspect.custom'); +const denoInspect = Symbol.for('Deno.customInspect'); + +const stringMethods = new Set(Reflect.ownKeys(String.prototype).filter((k) => typeof k === 'string')); +const numberMethods = new Set(Reflect.ownKeys(Number.prototype).filter((k) => typeof k === 'string')); +const arrayMethods = new Set(Reflect.ownKeys(Array.prototype).filter((k) => typeof k === 'string')); + +function getApplyKinds(name?: string | symbol): readonly Kind[] { + if (!name || name === nodeInspect || name === denoInspect) { + return allKinds; + } + + if (name === Symbol.toPrimitive || name === 'toString' || name === 'valueOf') { + return ['string', 'number', 'boolean']; + } + + if (name === Symbol.iterator) { + return ['array']; + } + + if (typeof name !== 'string') { + return ['method']; + } + + const kinds: Kind[] = []; + if (stringMethods.has(name)) { + kinds.push('string'); + } else if (numberMethods.has(name)) { + kinds.push('number'); + } else if (arrayMethods.has(name)) { + kinds.push('array'); + } + + return kinds.length > 0 ? kinds : ['method']; +} + +type KindPaths = Record; + +function traverseKinds( + obj: object, + path: string = '', + result: KindPaths = { + string: [], + number: [], + boolean: [], + object: [], + array: [], + method: [], + constructor: [], + }, +): KindPaths { + while (obj !== null) { + for (const key of Reflect.ownKeys(obj)) { + if (typeof key !== 'string') { + continue; + } + + if (key === 'constructor') { + continue; + } + + if (!/^[a-zA-Z]/.test(key)) { + continue; + } + + const value = Reflect.get(obj, key); + let kind: Kind; + + switch (typeof value) { + case 'string': { + kind = 'string'; + break; + } + case 'number': + case 'bigint': { + kind = 'number'; + break; + } + case 'boolean': { + kind = 'boolean'; + break; + } + case 'object': { + if (value === null) { + continue; + } + kind = Array.isArray(value) ? 'array' : 'object'; + break; + } + case 'function': { + kind = + key === value.name && value.name === value.prototype?.constructor?.name ? + 'constructor' + : 'method'; + break; + } + default: { + continue; + } + } + + const fullKey = path ? `${path}.${key}` : key; + result[kind].push(fullKey); + + if (kind === 'object') { + traverseKinds(value, fullKey, result); + } else if (kind === 'array' && value.length > 0) { + traverseKinds(value[0], `${fullKey}[]`, result); + } + } + + obj = Object.getPrototypeOf(obj); + if (obj === Object.prototype || obj === Array.prototype) { + break; + } + } + + return result; +} + +export type MakeError = (props: { + expected: readonly Kind[]; + rootPath: (string | symbol)[]; + path: (string | symbol)[]; + suggestions: { item: string; score: number }[]; +}) => string; + +export type ProxyConfig = { + /** + * Whether to also proxy the return values. They will be proxied with + * the same config, except the root path will be blank. Defaults to true. + */ + proxyReturn?: boolean; + /** + * The path to the root object, prepended to path suggestions. For example, + * if this is set to ['client'], then suggestions will be 'client.repos.list', + * 'client.users.list', etc. + */ + rootPath?: (string | symbol)[]; + /** + * Customize the error message to be thrown. The root path will not be + * prepended to either the path or the suggestions. + */ + makeSuggestionError?: MakeError; +}; + +function shouldProxy(value: unknown): value is NonNullable { + return value !== null && (typeof value === 'object' || typeof value === 'function'); +} + +const emptyTargetSymbol = Symbol.for('did-you-mean-proxy.emptyTargetPath'); + +type EmptyTarget = { + [emptyTargetSymbol]: { + getError: () => string; + }; +}; +type EmptyTargetInfo = EmptyTarget[typeof emptyTargetSymbol]; + +/** + * We use a special empty target so we can catch calls and constructions. + * Also useful for de-proxying in the end; if we get an empty target, we know + * we can throw an error. + */ +function createEmptyTarget(info: EmptyTargetInfo): EmptyTarget { + const emptyTarget = function () {} as any; + emptyTarget[nodeInspect] = () => { + throw info.getError(); + }; + emptyTarget[denoInspect] = () => { + throw info.getError(); + }; + emptyTarget[emptyTargetSymbol] = info; + return emptyTarget; +} + +function isEmptyTarget(value: unknown): value is EmptyTarget { + return typeof value === 'function' && (value as any)[emptyTargetSymbol] !== undefined; +} + +export const defaultMakeError: MakeError = function ({ expected, rootPath, path, suggestions }) { + const rootPathString = + rootPath.length > 0 ? `${rootPath.filter((p) => typeof p === 'string').join('.')}.` : ''; + const pathString = `'${rootPathString}${path.filter((p) => typeof p === 'string').join('.')}'`; + + let header = `${pathString} does not exist.`; + if (expected.length === 1) { + const expectedType = + expected[0] === 'array' ? 'an array' + : expected[0] === 'object' ? 'an object' + : expected[0] === 'method' ? 'a function' + : `a ${expected[0]}`; + header = `${pathString} is not ${expectedType}.`; + } + + const suggestionStrings = suggestions + // TODO(sometime): thresholding? + .filter((suggestion) => suggestion.score < 1) + .slice(0, 5) + .map((suggestion) => `'${rootPathString}${suggestion.item}'`); + + let body = ''; + if (suggestionStrings.length === 1) { + body = `Did you mean ${suggestionStrings[0]}?`; + } else if (suggestionStrings.length > 1) { + const commas = suggestionStrings.slice(0, suggestionStrings.length - 1).join(', '); + body = `Did you mean ${commas}, or ${suggestionStrings[suggestionStrings.length - 1]}?`; + } + + return body ? `${header} ${body}` : header; +}; + +export const debugMakeError: MakeError = function ({ expected, path, suggestions }) { + return `path ${path.filter((p) => typeof p === 'string').join('.')}; expected ${expected.join(', ')} +${suggestions + .slice(0, 10) + .map((suggestion) => ` - [${suggestion.score.toFixed(2)}] ${suggestion.item}`) + .join('\n')} +`; +}; + +const proxyToObj = new WeakMap(); + +export function makeProxy(root: Root, config: ProxyConfig = {}): Root { + let kindPaths: KindPaths | null = null; + + config.proxyReturn ??= true; + config.rootPath ??= ['']; + config.makeSuggestionError ??= defaultMakeError; + + const { proxyReturn, rootPath, makeSuggestionError } = config; + const { rootPath: _, ...subconfig } = config; + + function makeError(pathWithRoot: (string | symbol)[], expected: readonly Kind[]) { + if (!kindPaths) { + kindPaths = traverseKinds(root); + } + + const fuse = new Fuse( + expected.flatMap((kind) => kindPaths![kind]), + { includeScore: true }, + ); + + const path = pathWithRoot.slice(rootPath.length); + const searchKey: string[] = []; + for (const key of path) { + // Convert array keys to []: + if (/^\d+$/.test(key.toString())) { + searchKey.push('[]'); + } else if (typeof key === 'string') { + searchKey.push('.'); + searchKey.push(key); + } + } + + const key = searchKey.join(''); + const suggestions = fuse.search(key.slice(1)) as { item: string; score: number }[]; + + return makeSuggestionError({ expected, rootPath, path, suggestions }); + } + + function subproxy(obj: T, path: (string | symbol)[]): T { + const handlers: ProxyHandler = { + get(target, prop, receiver) { + const newPath = [...path, prop]; + const value = Reflect.get(target, prop, receiver); + + if (value === undefined && !Reflect.has(target, prop)) { + // Some common special cases: + // - 'then' is called on a non-thenable. + // - 'toJSON' is called when it's not defined. + // In these cases, we actually want to return undefined, so we + // resolve to the top-level thing. + if (prop === 'then' || prop === 'toJSON') { + return undefined; + } + + return subproxy( + createEmptyTarget({ + getError: () => makeError(newPath, allKinds), + }), + newPath, + ); + } + + return shouldProxy(value) ? subproxy(value, newPath) : value; + }, + construct(target, args, newTarget) { + if (isEmptyTarget(target) || typeof target !== 'function') { + throw new Error(makeError(path, ['constructor'])); + } + + const result = Reflect.construct(target, args, newTarget); + + return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; + }, + apply(target, thisArg, args) { + if (isEmptyTarget(target) || typeof target !== 'function') { + throw new Error(makeError(path, getApplyKinds(path[path.length - 1]))); + } + + const correctThisArg = proxyToObj.get(thisArg) ?? thisArg; + const proxiedArgs = + proxyReturn ? args.map((arg) => (shouldProxy(arg) ? makeProxy(arg, subconfig) : arg)) : args; + const result = Reflect.apply(target, correctThisArg, proxiedArgs); + + return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; + }, + }; + + // All other traps demand a non-empty target: + for (const trap of [ + 'defineProperty', + 'has', + 'set', + 'deleteProperty', + 'ownKeys', + 'getPrototypeOf', + 'setPrototypeOf', + 'isExtensible', + 'preventExtensions', + 'getOwnPropertyDescriptor', + ] as const) { + handlers[trap] = function (target: any, ...args: any[]) { + if (isEmptyTarget(target)) { + throw new Error(makeError(path, allKinds)); + } + + return (Reflect[trap] as any)(target, ...args); + }; + } + + const proxy = new Proxy(obj, handlers); + proxyToObj.set(proxy, obj); + + return proxy; + } + + return subproxy(root, rootPath); +} + +export function deproxy(value: T): T { + // Primitives never get proxied, so these are safe: + if (typeof value !== 'object' && typeof value !== 'function') { + return value; + } + if (isEmptyTarget(value)) { + throw new Error(value[emptyTargetSymbol].getError()); + } + return proxyToObj.get(value) ?? value; +} diff --git a/src/internal/polyfill/file.node.d.ts b/src/internal/polyfill/file.node.d.ts new file mode 100644 index 0000000..c95276d --- /dev/null +++ b/src/internal/polyfill/file.node.d.ts @@ -0,0 +1,14 @@ +/** + * This file polyfills the global `File` object for you if it's not already defined + * when running on Node.js + * + * This is only needed on Node.js v18 & v19. Newer versions already define `File` + * as a global. + */ + +// @ts-ignore +type nodeBuffer = typeof import('node:buffer'); +declare const File: typeof globalThis extends { File: unknown } ? (typeof globalThis)['File'] +: nodeBuffer extends { File: unknown } ? nodeBuffer['File'] +: any; +export {}; diff --git a/src/internal/polyfill/file.node.mjs b/src/internal/polyfill/file.node.mjs new file mode 100644 index 0000000..520dcb8 --- /dev/null +++ b/src/internal/polyfill/file.node.mjs @@ -0,0 +1,9 @@ +/** + * This file polyfills the global `File` object for you if it's not already defined + * when running on Node.js + * + * This is only needed on Node.js v18 & v19. Newer versions already define `File` + * as a global. + */ + +import './file.node.js'; diff --git a/tests/responses.test.ts b/tests/responses.test.ts new file mode 100644 index 0000000..2259dc0 --- /dev/null +++ b/tests/responses.test.ts @@ -0,0 +1,24 @@ +import { createResponseHeaders } from '@beeper/desktop-api/internal/headers'; + +describe('response parsing', () => { + // TODO: test unicode characters + test('headers are case agnostic', async () => { + const headers = createResponseHeaders(new Headers({ 'Content-Type': 'foo', Accept: 'text/plain' })); + expect(headers['content-type']).toEqual('foo'); + expect(headers['Content-type']).toEqual('foo'); + expect(headers['Content-Type']).toEqual('foo'); + expect(headers['accept']).toEqual('text/plain'); + expect(headers['Accept']).toEqual('text/plain'); + expect(headers['Hello-World']).toBeUndefined(); + }); + + test('duplicate headers are concatenated', () => { + const headers = createResponseHeaders( + new Headers([ + ['Content-Type', 'text/xml'], + ['Content-Type', 'application/json'], + ]), + ); + expect(headers['content-type']).toBe('text/xml, application/json'); + }); +}); From a44f1e6e5afca1513ef3484f853fe45599e4a1ee Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 6 Dec 2025 03:41:27 +0000 Subject: [PATCH 15/16] chore(internal): codegen related update --- .devcontainer/Dockerfile | 23 -- .eslintrc.js | 10 - jest.setup.ts | 0 packages/mcp-server/src/did-you-mean-proxy.ts | 356 ------------------ src/internal/polyfill/file.node.d.ts | 14 - src/internal/polyfill/file.node.mjs | 9 - tests/responses.test.ts | 24 -- 7 files changed, 436 deletions(-) delete mode 100644 .devcontainer/Dockerfile delete mode 100644 .eslintrc.js delete mode 100644 jest.setup.ts delete mode 100644 packages/mcp-server/src/did-you-mean-proxy.ts delete mode 100644 src/internal/polyfill/file.node.d.ts delete mode 100644 src/internal/polyfill/file.node.mjs delete mode 100644 tests/responses.test.ts diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile deleted file mode 100644 index 8ea34be..0000000 --- a/.devcontainer/Dockerfile +++ /dev/null @@ -1,23 +0,0 @@ -# syntax=docker/dockerfile:1 -FROM debian:bookworm-slim AS stainless - -RUN apt-get update && apt-get install -y \ - nodejs \ - npm \ - yarnpkg \ - && apt-get clean autoclean - -# Ensure UTF-8 encoding -ENV LANG=C.UTF-8 -ENV LC_ALL=C.UTF-8 - -# Yarn -RUN ln -sf /usr/bin/yarnpkg /usr/bin/yarn - -WORKDIR /workspace - -COPY package.json yarn.lock /workspace/ - -RUN yarn install - -COPY . /workspace diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 60f0e7a..0000000 --- a/.eslintrc.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - parser: '@typescript-eslint/parser', - plugins: ['@typescript-eslint', 'unused-imports', 'prettier'], - rules: { - 'no-unused-vars': 'off', - 'prettier/prettier': 'error', - 'unused-imports/no-unused-imports': 'error', - }, - root: true, -}; diff --git a/jest.setup.ts b/jest.setup.ts deleted file mode 100644 index e69de29..0000000 diff --git a/packages/mcp-server/src/did-you-mean-proxy.ts b/packages/mcp-server/src/did-you-mean-proxy.ts deleted file mode 100644 index 8c1380d..0000000 --- a/packages/mcp-server/src/did-you-mean-proxy.ts +++ /dev/null @@ -1,356 +0,0 @@ -import Fuse from 'fuse.js'; - -const allKinds = ['string', 'number', 'boolean', 'object', 'array', 'method', 'constructor'] as const; -type Kind = (typeof allKinds)[number]; - -const nodeInspect = Symbol.for('nodejs.util.inspect.custom'); -const denoInspect = Symbol.for('Deno.customInspect'); - -const stringMethods = new Set(Reflect.ownKeys(String.prototype).filter((k) => typeof k === 'string')); -const numberMethods = new Set(Reflect.ownKeys(Number.prototype).filter((k) => typeof k === 'string')); -const arrayMethods = new Set(Reflect.ownKeys(Array.prototype).filter((k) => typeof k === 'string')); - -function getApplyKinds(name?: string | symbol): readonly Kind[] { - if (!name || name === nodeInspect || name === denoInspect) { - return allKinds; - } - - if (name === Symbol.toPrimitive || name === 'toString' || name === 'valueOf') { - return ['string', 'number', 'boolean']; - } - - if (name === Symbol.iterator) { - return ['array']; - } - - if (typeof name !== 'string') { - return ['method']; - } - - const kinds: Kind[] = []; - if (stringMethods.has(name)) { - kinds.push('string'); - } else if (numberMethods.has(name)) { - kinds.push('number'); - } else if (arrayMethods.has(name)) { - kinds.push('array'); - } - - return kinds.length > 0 ? kinds : ['method']; -} - -type KindPaths = Record; - -function traverseKinds( - obj: object, - path: string = '', - result: KindPaths = { - string: [], - number: [], - boolean: [], - object: [], - array: [], - method: [], - constructor: [], - }, -): KindPaths { - while (obj !== null) { - for (const key of Reflect.ownKeys(obj)) { - if (typeof key !== 'string') { - continue; - } - - if (key === 'constructor') { - continue; - } - - if (!/^[a-zA-Z]/.test(key)) { - continue; - } - - const value = Reflect.get(obj, key); - let kind: Kind; - - switch (typeof value) { - case 'string': { - kind = 'string'; - break; - } - case 'number': - case 'bigint': { - kind = 'number'; - break; - } - case 'boolean': { - kind = 'boolean'; - break; - } - case 'object': { - if (value === null) { - continue; - } - kind = Array.isArray(value) ? 'array' : 'object'; - break; - } - case 'function': { - kind = - key === value.name && value.name === value.prototype?.constructor?.name ? - 'constructor' - : 'method'; - break; - } - default: { - continue; - } - } - - const fullKey = path ? `${path}.${key}` : key; - result[kind].push(fullKey); - - if (kind === 'object') { - traverseKinds(value, fullKey, result); - } else if (kind === 'array' && value.length > 0) { - traverseKinds(value[0], `${fullKey}[]`, result); - } - } - - obj = Object.getPrototypeOf(obj); - if (obj === Object.prototype || obj === Array.prototype) { - break; - } - } - - return result; -} - -export type MakeError = (props: { - expected: readonly Kind[]; - rootPath: (string | symbol)[]; - path: (string | symbol)[]; - suggestions: { item: string; score: number }[]; -}) => string; - -export type ProxyConfig = { - /** - * Whether to also proxy the return values. They will be proxied with - * the same config, except the root path will be blank. Defaults to true. - */ - proxyReturn?: boolean; - /** - * The path to the root object, prepended to path suggestions. For example, - * if this is set to ['client'], then suggestions will be 'client.repos.list', - * 'client.users.list', etc. - */ - rootPath?: (string | symbol)[]; - /** - * Customize the error message to be thrown. The root path will not be - * prepended to either the path or the suggestions. - */ - makeSuggestionError?: MakeError; -}; - -function shouldProxy(value: unknown): value is NonNullable { - return value !== null && (typeof value === 'object' || typeof value === 'function'); -} - -const emptyTargetSymbol = Symbol.for('did-you-mean-proxy.emptyTargetPath'); - -type EmptyTarget = { - [emptyTargetSymbol]: { - getError: () => string; - }; -}; -type EmptyTargetInfo = EmptyTarget[typeof emptyTargetSymbol]; - -/** - * We use a special empty target so we can catch calls and constructions. - * Also useful for de-proxying in the end; if we get an empty target, we know - * we can throw an error. - */ -function createEmptyTarget(info: EmptyTargetInfo): EmptyTarget { - const emptyTarget = function () {} as any; - emptyTarget[nodeInspect] = () => { - throw info.getError(); - }; - emptyTarget[denoInspect] = () => { - throw info.getError(); - }; - emptyTarget[emptyTargetSymbol] = info; - return emptyTarget; -} - -function isEmptyTarget(value: unknown): value is EmptyTarget { - return typeof value === 'function' && (value as any)[emptyTargetSymbol] !== undefined; -} - -export const defaultMakeError: MakeError = function ({ expected, rootPath, path, suggestions }) { - const rootPathString = - rootPath.length > 0 ? `${rootPath.filter((p) => typeof p === 'string').join('.')}.` : ''; - const pathString = `'${rootPathString}${path.filter((p) => typeof p === 'string').join('.')}'`; - - let header = `${pathString} does not exist.`; - if (expected.length === 1) { - const expectedType = - expected[0] === 'array' ? 'an array' - : expected[0] === 'object' ? 'an object' - : expected[0] === 'method' ? 'a function' - : `a ${expected[0]}`; - header = `${pathString} is not ${expectedType}.`; - } - - const suggestionStrings = suggestions - // TODO(sometime): thresholding? - .filter((suggestion) => suggestion.score < 1) - .slice(0, 5) - .map((suggestion) => `'${rootPathString}${suggestion.item}'`); - - let body = ''; - if (suggestionStrings.length === 1) { - body = `Did you mean ${suggestionStrings[0]}?`; - } else if (suggestionStrings.length > 1) { - const commas = suggestionStrings.slice(0, suggestionStrings.length - 1).join(', '); - body = `Did you mean ${commas}, or ${suggestionStrings[suggestionStrings.length - 1]}?`; - } - - return body ? `${header} ${body}` : header; -}; - -export const debugMakeError: MakeError = function ({ expected, path, suggestions }) { - return `path ${path.filter((p) => typeof p === 'string').join('.')}; expected ${expected.join(', ')} -${suggestions - .slice(0, 10) - .map((suggestion) => ` - [${suggestion.score.toFixed(2)}] ${suggestion.item}`) - .join('\n')} -`; -}; - -const proxyToObj = new WeakMap(); - -export function makeProxy(root: Root, config: ProxyConfig = {}): Root { - let kindPaths: KindPaths | null = null; - - config.proxyReturn ??= true; - config.rootPath ??= ['']; - config.makeSuggestionError ??= defaultMakeError; - - const { proxyReturn, rootPath, makeSuggestionError } = config; - const { rootPath: _, ...subconfig } = config; - - function makeError(pathWithRoot: (string | symbol)[], expected: readonly Kind[]) { - if (!kindPaths) { - kindPaths = traverseKinds(root); - } - - const fuse = new Fuse( - expected.flatMap((kind) => kindPaths![kind]), - { includeScore: true }, - ); - - const path = pathWithRoot.slice(rootPath.length); - const searchKey: string[] = []; - for (const key of path) { - // Convert array keys to []: - if (/^\d+$/.test(key.toString())) { - searchKey.push('[]'); - } else if (typeof key === 'string') { - searchKey.push('.'); - searchKey.push(key); - } - } - - const key = searchKey.join(''); - const suggestions = fuse.search(key.slice(1)) as { item: string; score: number }[]; - - return makeSuggestionError({ expected, rootPath, path, suggestions }); - } - - function subproxy(obj: T, path: (string | symbol)[]): T { - const handlers: ProxyHandler = { - get(target, prop, receiver) { - const newPath = [...path, prop]; - const value = Reflect.get(target, prop, receiver); - - if (value === undefined && !Reflect.has(target, prop)) { - // Some common special cases: - // - 'then' is called on a non-thenable. - // - 'toJSON' is called when it's not defined. - // In these cases, we actually want to return undefined, so we - // resolve to the top-level thing. - if (prop === 'then' || prop === 'toJSON') { - return undefined; - } - - return subproxy( - createEmptyTarget({ - getError: () => makeError(newPath, allKinds), - }), - newPath, - ); - } - - return shouldProxy(value) ? subproxy(value, newPath) : value; - }, - construct(target, args, newTarget) { - if (isEmptyTarget(target) || typeof target !== 'function') { - throw new Error(makeError(path, ['constructor'])); - } - - const result = Reflect.construct(target, args, newTarget); - - return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; - }, - apply(target, thisArg, args) { - if (isEmptyTarget(target) || typeof target !== 'function') { - throw new Error(makeError(path, getApplyKinds(path[path.length - 1]))); - } - - const correctThisArg = proxyToObj.get(thisArg) ?? thisArg; - const proxiedArgs = - proxyReturn ? args.map((arg) => (shouldProxy(arg) ? makeProxy(arg, subconfig) : arg)) : args; - const result = Reflect.apply(target, correctThisArg, proxiedArgs); - - return proxyReturn && shouldProxy(result) ? makeProxy(result, subconfig) : result; - }, - }; - - // All other traps demand a non-empty target: - for (const trap of [ - 'defineProperty', - 'has', - 'set', - 'deleteProperty', - 'ownKeys', - 'getPrototypeOf', - 'setPrototypeOf', - 'isExtensible', - 'preventExtensions', - 'getOwnPropertyDescriptor', - ] as const) { - handlers[trap] = function (target: any, ...args: any[]) { - if (isEmptyTarget(target)) { - throw new Error(makeError(path, allKinds)); - } - - return (Reflect[trap] as any)(target, ...args); - }; - } - - const proxy = new Proxy(obj, handlers); - proxyToObj.set(proxy, obj); - - return proxy; - } - - return subproxy(root, rootPath); -} - -export function deproxy(value: T): T { - // Primitives never get proxied, so these are safe: - if (typeof value !== 'object' && typeof value !== 'function') { - return value; - } - if (isEmptyTarget(value)) { - throw new Error(value[emptyTargetSymbol].getError()); - } - return proxyToObj.get(value) ?? value; -} diff --git a/src/internal/polyfill/file.node.d.ts b/src/internal/polyfill/file.node.d.ts deleted file mode 100644 index c95276d..0000000 --- a/src/internal/polyfill/file.node.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * This file polyfills the global `File` object for you if it's not already defined - * when running on Node.js - * - * This is only needed on Node.js v18 & v19. Newer versions already define `File` - * as a global. - */ - -// @ts-ignore -type nodeBuffer = typeof import('node:buffer'); -declare const File: typeof globalThis extends { File: unknown } ? (typeof globalThis)['File'] -: nodeBuffer extends { File: unknown } ? nodeBuffer['File'] -: any; -export {}; diff --git a/src/internal/polyfill/file.node.mjs b/src/internal/polyfill/file.node.mjs deleted file mode 100644 index 520dcb8..0000000 --- a/src/internal/polyfill/file.node.mjs +++ /dev/null @@ -1,9 +0,0 @@ -/** - * This file polyfills the global `File` object for you if it's not already defined - * when running on Node.js - * - * This is only needed on Node.js v18 & v19. Newer versions already define `File` - * as a global. - */ - -import './file.node.js'; diff --git a/tests/responses.test.ts b/tests/responses.test.ts deleted file mode 100644 index 2259dc0..0000000 --- a/tests/responses.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { createResponseHeaders } from '@beeper/desktop-api/internal/headers'; - -describe('response parsing', () => { - // TODO: test unicode characters - test('headers are case agnostic', async () => { - const headers = createResponseHeaders(new Headers({ 'Content-Type': 'foo', Accept: 'text/plain' })); - expect(headers['content-type']).toEqual('foo'); - expect(headers['Content-type']).toEqual('foo'); - expect(headers['Content-Type']).toEqual('foo'); - expect(headers['accept']).toEqual('text/plain'); - expect(headers['Accept']).toEqual('text/plain'); - expect(headers['Hello-World']).toBeUndefined(); - }); - - test('duplicate headers are concatenated', () => { - const headers = createResponseHeaders( - new Headers([ - ['Content-Type', 'text/xml'], - ['Content-Type', 'application/json'], - ]), - ); - expect(headers['content-type']).toBe('text/xml, application/json'); - }); -}); From 7638f9099876265cfd0a3c2a6d658cc0cf42620b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 6 Dec 2025 03:41:43 +0000 Subject: [PATCH 16/16] release: 4.3.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 30 ++++++++++++++++++++++++++++++ package.json | 2 +- packages/mcp-server/package.json | 2 +- packages/mcp-server/src/server.ts | 2 +- src/version.ts | 2 +- 6 files changed, 35 insertions(+), 5 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9022474..83f9eb8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "4.2.3" + ".": "4.3.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index ae58e82..98b9d0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,35 @@ # Changelog +## 4.3.0 (2025-12-06) + +Full Changelog: [v4.2.3...v4.3.0](https://github.com/beeper/desktop-api-js/compare/v4.2.3...v4.3.0) + +### Features + +* **mcp:** add detail field to docs search tool ([94efb53](https://github.com/beeper/desktop-api-js/commit/94efb539eb6279bd5e8076e9652aaac821d7e465)) +* **mcp:** add typescript check to code execution tool ([dd5606a](https://github.com/beeper/desktop-api-js/commit/dd5606aeb6f72a2b7383a7a52d47a3786adb7fe8)) +* **mcp:** handle code mode calls in the Stainless API ([0583d4a](https://github.com/beeper/desktop-api-js/commit/0583d4a1b97f825d9c3e76c9eae155d09e108f4c)) +* **mcp:** return logs on code tool errors ([d635e28](https://github.com/beeper/desktop-api-js/commit/d635e28ce32796e0e71b8ee21a579fbca061f1f5)) + + +### Bug Fixes + +* **mcp:** correct code tool API endpoint ([e4d8fd3](https://github.com/beeper/desktop-api-js/commit/e4d8fd374547a678ae125358bcbc52f092df00cb)) +* **mcp:** return correct lines on typescript errors ([2670800](https://github.com/beeper/desktop-api-js/commit/267080003620b463563fbe0fa1808a12d471a692)) +* **mcp:** return tool execution error on api error ([7886dae](https://github.com/beeper/desktop-api-js/commit/7886dae7ae5da785ef4bea988f253e35007ee16a)) +* **mcp:** return tool execution error on jq failure ([cadbf31](https://github.com/beeper/desktop-api-js/commit/cadbf3111d4aff52467527cbad99abba90164cc8)) + + +### Chores + +* **client:** fix logger property type ([6ecc636](https://github.com/beeper/desktop-api-js/commit/6ecc636c5e0c2a2aeaed7da6e57a1663b3d711e7)) +* **internal:** codegen related update ([a44f1e6](https://github.com/beeper/desktop-api-js/commit/a44f1e6e5afca1513ef3484f853fe45599e4a1ee)) +* **internal:** codegen related update ([6148100](https://github.com/beeper/desktop-api-js/commit/61481002797da513cdf64b33161fb6399de710aa)) +* **internal:** upgrade eslint ([7256acf](https://github.com/beeper/desktop-api-js/commit/7256acf2e8fdd02aae2b169e15547fddb10fb250)) +* **mcp:** clarify http auth error ([79374fd](https://github.com/beeper/desktop-api-js/commit/79374fd11b48ad2c96097184b492b6f6f7710593)) +* **mcp:** upgrade jq-web ([298fec2](https://github.com/beeper/desktop-api-js/commit/298fec2720697f7c36077104a2325ecd05d9a839)) +* use latest @modelcontextprotocol/sdk ([6400f79](https://github.com/beeper/desktop-api-js/commit/6400f79bf4d6fd5bc46a11ccf2336327910a39e9)) + ## 4.2.3 (2025-11-08) Full Changelog: [v4.2.2...v4.2.3](https://github.com/beeper/desktop-api-js/compare/v4.2.2...v4.2.3) diff --git a/package.json b/package.json index fa42669..a30d699 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@beeper/desktop-api", - "version": "4.2.3", + "version": "4.3.0", "description": "The official TypeScript library for the Beeper Desktop API", "author": "Beeper Desktop ", "types": "dist/index.d.ts", diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 75ec3a3..5f3235c 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "@beeper/desktop-mcp", - "version": "4.2.3", + "version": "4.3.0", "description": "The official MCP Server for the Beeper Desktop API", "author": "Beeper Desktop ", "types": "dist/index.d.ts", diff --git a/packages/mcp-server/src/server.ts b/packages/mcp-server/src/server.ts index a85a1b0..5c42bec 100644 --- a/packages/mcp-server/src/server.ts +++ b/packages/mcp-server/src/server.ts @@ -34,7 +34,7 @@ export const newMcpServer = () => new McpServer( { name: 'beeper_desktop_api_api', - version: '4.2.3', + version: '4.3.0', }, { capabilities: { tools: {}, logging: {} }, diff --git a/src/version.ts b/src/version.ts index 68e3e2c..e743242 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '4.2.3'; // x-release-please-version +export const VERSION = '4.3.0'; // x-release-please-version