diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..12ff1e64 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,59 @@ +# Dependencies +node_modules/ +**/node_modules/ + +# Build outputs +dist/ +**/dist/ + +# Git +.git/ +.gitignore + +# CI/CD +.github/ +.gitlab-ci.yml +.travis.yml + +# IDE +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Testing +test/ +tests/ +__tests__/ +*.test.js +*.spec.js +coverage/ +.nyc_output/ + +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Environment +.env +.env.* + +# Temporary files +*.tmp +*.temp +.cache/ + +# Examples and scripts +examples/ +bin/ + +# Other packages (we only need mcp-server) +packages/*/ +!packages/mcp-server/ diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 92856693..9695e0ec 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "9.0.0" + ".": "9.1.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 7589c280..e4e3e70d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Changelog +## 9.1.0 (2026-02-11) + +Full Changelog: [v9.0.0...v9.1.0](https://github.com/Finch-API/finch-api-node/compare/v9.0.0...v9.1.0) + +### Features + +* **mcp:** add initial server instructions ([41a62e7](https://github.com/Finch-API/finch-api-node/commit/41a62e7da2c6f6fe1b59afe8d87066489d707bc4)) + + +### Bug Fixes + +* **client:** avoid memory leak with abort signals ([e6cbcb4](https://github.com/Finch-API/finch-api-node/commit/e6cbcb4c380d391797875514114fbd870e680aa9)) +* **client:** avoid removing abort listener too early ([834599b](https://github.com/Finch-API/finch-api-node/commit/834599b8d10c0cc7858861504ebbc6142d28768d)) +* **docs:** fix mcp installation instructions for remote servers ([2346e45](https://github.com/Finch-API/finch-api-node/commit/2346e45e51546112f96d29f89904a499c66c61d2)) +* **mcp:** allow falling back for required env variables ([e2285bf](https://github.com/Finch-API/finch-api-node/commit/e2285bffd1403ecbb223daf47f7e1eda40033d54)) + + +### Chores + +* **client:** do not parse responses with empty content-length ([9168b0e](https://github.com/Finch-API/finch-api-node/commit/9168b0e266bb4babc638698f27c166d282c5f346)) +* **client:** restructure abort controller binding ([03776eb](https://github.com/Finch-API/finch-api-node/commit/03776eb5c0329b6580fb3c2e58ce4d811fbde635)) +* **internal:** add health check to MCP server when running in HTTP mode ([c6b1999](https://github.com/Finch-API/finch-api-node/commit/c6b1999a1895466414ad1c3975b27ee317faa473)) +* **internal:** allow basic filtering of methods allowed for MCP code mode ([c6921b7](https://github.com/Finch-API/finch-api-node/commit/c6921b76e9db6ddd6019353a6da69c12a43f8570)) +* **internal:** always generate MCP server dockerfiles and upgrade associated dependencies ([d786340](https://github.com/Finch-API/finch-api-node/commit/d7863401c96e70f832d74a7eca4b7ef0850791e2)) +* **internal:** avoid type checking errors with ts-reset ([ec27092](https://github.com/Finch-API/finch-api-node/commit/ec270924322d2fbb055eb36ae6b8b75c2102f89a)) +* **internal:** codegen related update ([b3f5e09](https://github.com/Finch-API/finch-api-node/commit/b3f5e099f190c0dcdd648262398d4629fac02671)) +* **internal:** fix pagination internals not accepting option promises ([6b75209](https://github.com/Finch-API/finch-api-node/commit/6b7520906d83f1ebeaf76c2b827f34f8ebeeeca2)) +* **internal:** refactor flag parsing for MCP servers and add debug flag ([c3685d5](https://github.com/Finch-API/finch-api-node/commit/c3685d56e5988db461e09f3ec90e693dbec3bdfa)) +* **internal:** support oauth authorization code flow for MCP servers ([ed2565a](https://github.com/Finch-API/finch-api-node/commit/ed2565a0da646b78e0f3d74bbe7d2f7c8c4c46bb)) +* **mcp:** up tsconfig lib version to es2022 ([b96b21e](https://github.com/Finch-API/finch-api-node/commit/b96b21eccc21170a8c655ac8de964723952e9f93)) + ## 9.0.0 (2026-01-27) Full Changelog: [v8.2.1...v9.0.0](https://github.com/Finch-API/finch-api-node/compare/v8.2.1...v9.0.0) diff --git a/README.md b/README.md index bdc25d51..760146bc 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ It is generated with [Stainless](https://www.stainless.com/). Use the Finch MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application. -[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40tryfinch%2Ffinch-api-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkB0cnlmaW5jaC9maW5jaC1hcGktbWNwIl19) -[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40tryfinch%2Ffinch-api-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40tryfinch%2Ffinch-api-mcp%22%5D%7D) +[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40tryfinch%2Ffinch-api-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkB0cnlmaW5jaC9maW5jaC1hcGktbWNwIl0sImVudiI6eyJGSU5DSF9BQ0NFU1NfVE9LRU4iOiJNeSBBY2Nlc3MgVG9rZW4iLCJGSU5DSF9DTElFTlRfSUQiOiI0YWIxNWU1MS0xMWFkLTQ5ZjQtYWNhZS1mMzQzYjc3OTQzNzUiLCJGSU5DSF9DTElFTlRfU0VDUkVUIjoiTXkgQ2xpZW50IFNlY3JldCIsIkZJTkNIX1dFQkhPT0tfU0VDUkVUIjoiTXkgV2ViaG9vayBTZWNyZXQifX0) +[![Install in VS Code](https://img.shields.io/badge/_-Add_to_VS_Code-blue?style=for-the-badge&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGZpbGw9Im5vbmUiIHZpZXdCb3g9IjAgMCA0MCA0MCI+PHBhdGggZmlsbD0iI0VFRSIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMzAuMjM1IDM5Ljg4NGEyLjQ5MSAyLjQ5MSAwIDAgMS0xLjc4MS0uNzNMMTIuNyAyNC43OGwtMy40NiAyLjYyNC0zLjQwNiAyLjU4MmExLjY2NSAxLjY2NSAwIDAgMS0xLjA4Mi4zMzggMS42NjQgMS42NjQgMCAwIDEtMS4wNDYtLjQzMWwtMi4yLTJhMS42NjYgMS42NjYgMCAwIDEgMC0yLjQ2M0w3LjQ1OCAyMCA0LjY3IDE3LjQ1MyAxLjUwNyAxNC41N2ExLjY2NSAxLjY2NSAwIDAgMSAwLTIuNDYzbDIuMi0yYTEuNjY1IDEuNjY1IDAgMCAxIDIuMTMtLjA5N2w2Ljg2MyA1LjIwOUwyOC40NTIuODQ0YTIuNDg4IDIuNDg4IDAgMCAxIDEuODQxLS43MjljLjM1MS4wMDkuNjk5LjA5MSAxLjAxOS4yNDVsOC4yMzYgMy45NjFhMi41IDIuNSAwIDAgMSAxLjQxNSAyLjI1M3YuMDk5LS4wNDVWMzMuMzd2LS4wNDUuMDk1YTIuNTAxIDIuNTAxIDAgMCAxLTEuNDE2IDIuMjU3bC04LjIzNSAzLjk2MWEyLjQ5MiAyLjQ5MiAwIDAgMS0xLjA3Ny4yNDZabS43MTYtMjguOTQ3LTExLjk0OCA5LjA2MiAxMS45NTIgOS4wNjUtLjAwNC0xOC4xMjdaIi8+PC9zdmc+)](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40tryfinch%2Ffinch-api-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40tryfinch%2Ffinch-api-mcp%22%5D%2C%22env%22%3A%7B%22FINCH_ACCESS_TOKEN%22%3A%22My%20Access%20Token%22%2C%22FINCH_CLIENT_ID%22%3A%224ab15e51-11ad-49f4-acae-f343b7794375%22%2C%22FINCH_CLIENT_SECRET%22%3A%22My%20Client%20Secret%22%2C%22FINCH_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%7D%7D) > Note: You may need to set environment variables in your MCP client. diff --git a/package.json b/package.json index 727a86fb..2cabc142 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@tryfinch/finch-api", - "version": "9.0.0", + "version": "9.1.0", "description": "The official TypeScript library for the Finch API", "author": "Finch ", "types": "dist/index.d.ts", diff --git a/packages/mcp-server/Dockerfile b/packages/mcp-server/Dockerfile new file mode 100644 index 00000000..193b657e --- /dev/null +++ b/packages/mcp-server/Dockerfile @@ -0,0 +1,71 @@ +# Dockerfile for Finch MCP Server +# +# This Dockerfile builds a Docker image for the MCP Server. +# +# To build the image locally: +# docker build -f packages/mcp-server/Dockerfile -t @tryfinch/finch-api-mcp:local . +# +# To run the image: +# docker run -i @tryfinch/finch-api-mcp:local [OPTIONS] +# +# Common options: +# --tool= Include specific tools +# --resource= Include tools for specific resources +# --operation=read|write Filter by operation type +# --client= Set client compatibility (e.g., claude, cursor) +# --transport= Set transport type (stdio or http) +# +# For a full list of options: +# docker run -i @tryfinch/finch-api-mcp:local --help +# +# Note: The MCP server uses stdio transport by default. Docker's -i flag +# enables interactive mode, allowing the container to communicate over stdin/stdout. + +# Build stage +FROM node:24-alpine AS builder + +# Install bash for build script +RUN apk add --no-cache bash openssl + +# Set working directory +WORKDIR /build + +# Copy entire repository +COPY . . + +# Install all dependencies and build everything +RUN yarn install --frozen-lockfile && \ + yarn build + +# Production stage +FROM node:24-alpine + +# Add non-root user +RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001 + +# Set working directory +WORKDIR /app + +# Copy the built mcp-server dist directory +COPY --from=builder /build/packages/mcp-server/dist ./ + +# Copy node_modules from mcp-server (includes all production deps) +COPY --from=builder /build/packages/mcp-server/node_modules ./node_modules + +# Copy the built @tryfinch/finch-api into node_modules +COPY --from=builder /build/dist ./node_modules/@tryfinch/finch-api + +# Change ownership to nodejs user +RUN chown -R nodejs:nodejs /app + +# Switch to non-root user +USER nodejs + +# The MCP server uses stdio transport by default +# No exposed ports needed for stdio communication + +# Set the entrypoint to the MCP server +ENTRYPOINT ["node", "index.js"] + +# Allow passing arguments to the MCP server +CMD [] diff --git a/packages/mcp-server/README.md b/packages/mcp-server/README.md index bb1e160f..07c2da90 100644 --- a/packages/mcp-server/README.md +++ b/packages/mcp-server/README.md @@ -45,14 +45,14 @@ For clients with a configuration JSON, it might look something like this: If you use Cursor, you can install the MCP server by using the button below. You will need to set your environment variables in Cursor's `mcp.json`, which can be found in Cursor Settings > Tools & MCP > New MCP Server. -[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40tryfinch%2Ffinch-api-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkB0cnlmaW5jaC9maW5jaC1hcGktbWNwIl0sImVudiI6eyJGSU5DSF9BQ0NFU1NfVE9LRU4iOiJTZXQgeW91ciBGSU5DSF9BQ0NFU1NfVE9LRU4gaGVyZS4iLCJGSU5DSF9DTElFTlRfSUQiOiJTZXQgeW91ciBGSU5DSF9DTElFTlRfSUQgaGVyZS4iLCJGSU5DSF9DTElFTlRfU0VDUkVUIjoiU2V0IHlvdXIgRklOQ0hfQ0xJRU5UX1NFQ1JFVCBoZXJlLiIsIkZJTkNIX1dFQkhPT0tfU0VDUkVUIjoiU2V0IHlvdXIgRklOQ0hfV0VCSE9PS19TRUNSRVQgaGVyZS4ifX0) +[![Add to Cursor](https://cursor.com/deeplink/mcp-install-dark.svg)](https://cursor.com/en-US/install-mcp?name=%40tryfinch%2Ffinch-api-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsIkB0cnlmaW5jaC9maW5jaC1hcGktbWNwIl0sImVudiI6eyJGSU5DSF9BQ0NFU1NfVE9LRU4iOiJNeSBBY2Nlc3MgVG9rZW4iLCJGSU5DSF9DTElFTlRfSUQiOiI0YWIxNWU1MS0xMWFkLTQ5ZjQtYWNhZS1mMzQzYjc3OTQzNzUiLCJGSU5DSF9DTElFTlRfU0VDUkVUIjoiTXkgQ2xpZW50IFNlY3JldCIsIkZJTkNIX1dFQkhPT0tfU0VDUkVUIjoiTXkgV2ViaG9vayBTZWNyZXQifX0) ### VS Code If you use MCP, you can install the MCP server by clicking the link below. You will need to set your environment variables in VS Code's `mcp.json`, which can be found via Command Palette > MCP: Open User Configuration. -[Open VS Code](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40tryfinch%2Ffinch-api-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40tryfinch%2Ffinch-api-mcp%22%5D%2C%22env%22%3A%7B%22FINCH_ACCESS_TOKEN%22%3A%22Set%20your%20FINCH_ACCESS_TOKEN%20here.%22%2C%22FINCH_CLIENT_ID%22%3A%22Set%20your%20FINCH_CLIENT_ID%20here.%22%2C%22FINCH_CLIENT_SECRET%22%3A%22Set%20your%20FINCH_CLIENT_SECRET%20here.%22%2C%22FINCH_WEBHOOK_SECRET%22%3A%22Set%20your%20FINCH_WEBHOOK_SECRET%20here.%22%7D%7D) +[Open VS Code](https://vscode.stainless.com/mcp/%7B%22name%22%3A%22%40tryfinch%2Ffinch-api-mcp%22%2C%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40tryfinch%2Ffinch-api-mcp%22%5D%2C%22env%22%3A%7B%22FINCH_ACCESS_TOKEN%22%3A%22My%20Access%20Token%22%2C%22FINCH_CLIENT_ID%22%3A%224ab15e51-11ad-49f4-acae-f343b7794375%22%2C%22FINCH_CLIENT_SECRET%22%3A%22My%20Client%20Secret%22%2C%22FINCH_WEBHOOK_SECRET%22%3A%22My%20Webhook%20Secret%22%7D%7D) ### Claude Code @@ -60,7 +60,7 @@ If you use Claude Code, you can install the MCP server by running the command be environment variables in Claude Code's `.claude.json`, which can be found in your home directory. ``` -claude mcp add tryfinch_finch_api_mcp_api --env FINCH_ACCESS_TOKEN="Your FINCH_ACCESS_TOKEN here." FINCH_CLIENT_ID="Your FINCH_CLIENT_ID here." FINCH_CLIENT_SECRET="Your FINCH_CLIENT_SECRET here." FINCH_WEBHOOK_SECRET="Your FINCH_WEBHOOK_SECRET here." -- npx -y @tryfinch/finch-api-mcp +claude mcp add tryfinch_finch_api_mcp_api --env FINCH_ACCESS_TOKEN="My Access Token" FINCH_CLIENT_ID="4ab15e51-11ad-49f4-acae-f343b7794375" FINCH_CLIENT_SECRET="My Client Secret" FINCH_WEBHOOK_SECRET="My Webhook Secret" -- npx -y @tryfinch/finch-api-mcp ``` ## Code Mode diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 5a8a75d0..9a60afd5 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "@tryfinch/finch-api-mcp", - "version": "9.0.0", + "version": "9.1.0", "description": "The official MCP Server for the Finch API", "author": "Finch ", "types": "dist/index.d.ts", @@ -34,10 +34,13 @@ "@cloudflare/cabidela": "^0.2.4", "@modelcontextprotocol/sdk": "^1.25.2", "@valtown/deno-http-worker": "^0.0.21", + "cookie-parser": "^1.4.6", "cors": "^2.8.5", "express": "^5.1.0", "fuse.js": "^7.1.0", "jq-web": "https://github.com/stainless-api/jq-web/releases/download/v0.8.8/jq-web.tar.gz", + "morgan": "^1.10.0", + "morgan-body": "^2.6.9", "qs": "^6.14.1", "typescript": "5.8.3", "yargs": "^17.7.2", @@ -50,9 +53,11 @@ }, "devDependencies": { "@anthropic-ai/mcpb": "^2.1.2", + "@types/cookie-parser": "^1.4.10", "@types/cors": "^2.8.19", "@types/express": "^5.0.3", "@types/jest": "^29.4.0", + "@types/morgan": "^1.9.10", "@types/qs": "^6.14.0", "@types/yargs": "^17.0.8", "@typescript-eslint/eslint-plugin": "8.31.1", diff --git a/packages/mcp-server/src/code-tool.ts b/packages/mcp-server/src/code-tool.ts index 6040f919..bff47edd 100644 --- a/packages/mcp-server/src/code-tool.ts +++ b/packages/mcp-server/src/code-tool.ts @@ -4,6 +4,8 @@ import { McpTool, Metadata, ToolCallResult, asErrorResult, asTextContentResult } import { Tool } from '@modelcontextprotocol/sdk/types.js'; import { readEnv } from './server'; import { WorkerInput, WorkerOutput } from './code-tool-types'; +import { SdkMethod } from './methods'; +import { Finch } from '@tryfinch/finch-api'; const prompt = `Runs JavaScript code to interact with the Finch API. @@ -35,7 +37,7 @@ Variables will not persist between calls, so make sure to return or log any data * * @param endpoints - The endpoints to include in the list. */ -export function codeTool(): McpTool { +export function codeTool(params: { blockedMethods: SdkMethod[] | undefined }): McpTool { const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] }; const tool: Tool = { name: 'execute', @@ -55,10 +57,28 @@ export function codeTool(): McpTool { required: ['code'], }, }; - const handler = async (_: unknown, args: any): Promise => { + const handler = async (client: Finch, args: any): Promise => { const code = args.code as string; const intent = args.intent as string | undefined; + // Do very basic blocking of code that includes forbidden method names. + // + // WARNING: This is not secure against obfuscation and other evasion methods. If + // stronger security blocks are required, then these should be enforced in the downstream + // API (e.g., by having users call the MCP server with API keys with limited permissions). + if (params.blockedMethods) { + const blockedMatches = params.blockedMethods.filter((method) => + code.includes(method.fullyQualifiedName), + ); + if (blockedMatches.length > 0) { + return asErrorResult( + `The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches + .map((m) => m.fullyQualifiedName) + .join(', ')}`, + ); + } + } + // 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'); @@ -71,10 +91,10 @@ export function codeTool(): McpTool { ...(stainlessAPIKey && { Authorization: stainlessAPIKey }), 'Content-Type': 'application/json', client_envs: JSON.stringify({ - FINCH_CLIENT_ID: readEnv('FINCH_CLIENT_ID'), - FINCH_CLIENT_SECRET: readEnv('FINCH_CLIENT_SECRET'), - FINCH_WEBHOOK_SECRET: readEnv('FINCH_WEBHOOK_SECRET'), - FINCH_BASE_URL: readEnv('FINCH_BASE_URL'), + FINCH_CLIENT_ID: readEnv('FINCH_CLIENT_ID') ?? client.clientID ?? undefined, + FINCH_CLIENT_SECRET: readEnv('FINCH_CLIENT_SECRET') ?? client.clientSecret ?? undefined, + FINCH_WEBHOOK_SECRET: readEnv('FINCH_WEBHOOK_SECRET') ?? client.webhookSecret ?? undefined, + FINCH_BASE_URL: readEnv('FINCH_BASE_URL') ?? client.baseURL ?? undefined, }), }, body: JSON.stringify({ diff --git a/packages/mcp-server/src/headers.ts b/packages/mcp-server/src/headers.ts index e127d4e8..5127806d 100644 --- a/packages/mcp-server/src/headers.ts +++ b/packages/mcp-server/src/headers.ts @@ -3,7 +3,7 @@ import { IncomingMessage } from 'node:http'; import { ClientOptions } from '@tryfinch/finch-api'; -export const parseAuthHeaders = (req: IncomingMessage): Partial => { +export const parseAuthHeaders = (req: IncomingMessage, required?: boolean): Partial => { if (req.headers.authorization) { const scheme = req.headers.authorization.split(' ')[0]!; const value = req.headers.authorization.slice(scheme.length + 1); @@ -21,6 +21,8 @@ export const parseAuthHeaders = (req: IncomingMessage): Partial = 'Unsupported authorization scheme. Expected the "Authorization" header to be a supported scheme (Bearer, Basic).', ); } + } else if (required) { + throw new Error('Missing required Authorization header; see WWW-Authenticate header for details.'); } const clientID = diff --git a/packages/mcp-server/src/http.ts b/packages/mcp-server/src/http.ts index dcfeba6a..8ca827c2 100644 --- a/packages/mcp-server/src/http.ts +++ b/packages/mcp-server/src/http.ts @@ -2,27 +2,31 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; - import express from 'express'; +import morgan from 'morgan'; +import morganBody from 'morgan-body'; import { McpOptions } from './options'; import { ClientOptions, initMcpServer, newMcpServer } from './server'; import { parseAuthHeaders } from './headers'; -const newServer = ({ +const newServer = async ({ clientOptions, + mcpOptions, req, res, }: { clientOptions: ClientOptions; + mcpOptions: McpOptions; req: express.Request; res: express.Response; -}): McpServer | null => { - const server = newMcpServer(); +}): Promise => { + const server = await newMcpServer(); try { - const authOptions = parseAuthHeaders(req); - initMcpServer({ + const authOptions = parseAuthHeaders(req, false); + await initMcpServer({ server: server, + mcpOptions: mcpOptions, clientOptions: { ...clientOptions, ...authOptions, @@ -45,7 +49,7 @@ const newServer = ({ const post = (options: { clientOptions: ClientOptions; mcpOptions: McpOptions }) => async (req: express.Request, res: express.Response) => { - const server = newServer({ ...options, req, res }); + const server = await newServer({ ...options, req, res }); // If we return null, we already set the authorization error. if (server === null) return; const transport = new StreamableHTTPServerTransport(); @@ -75,15 +79,31 @@ const del = async (req: express.Request, res: express.Response) => { export const streamableHTTPApp = ({ clientOptions = {}, - mcpOptions = {}, + mcpOptions, + debug, }: { clientOptions?: ClientOptions; - mcpOptions?: McpOptions; + mcpOptions: McpOptions; + debug: boolean; }): express.Express => { const app = express(); app.set('query parser', 'extended'); app.use(express.json()); + if (debug) { + morganBody(app, { + logAllReqHeader: true, + logAllResHeader: true, + logRequestBody: true, + logResponseBody: true, + }); + } else { + app.use(morgan('combined')); + } + + app.get('/health', async (req: express.Request, res: express.Response) => { + res.status(200).send('OK'); + }); app.get('/', get); app.post('/', post({ clientOptions, mcpOptions })); app.delete('/', del); @@ -91,9 +111,13 @@ export const streamableHTTPApp = ({ return app; }; -export const launchStreamableHTTPServer = async (options: McpOptions, port: number | string | undefined) => { - const app = streamableHTTPApp({ mcpOptions: options }); - const server = app.listen(port); +export const launchStreamableHTTPServer = async (params: { + mcpOptions: McpOptions; + debug: boolean; + port: number | string | undefined; +}) => { + const app = streamableHTTPApp({ mcpOptions: params.mcpOptions, debug: params.debug }); + const server = app.listen(params.port); const address = server.address(); if (typeof address === 'string') { @@ -101,6 +125,6 @@ export const launchStreamableHTTPServer = async (options: McpOptions, port: numb } else if (address !== null) { console.error(`MCP Server running on streamable HTTP on port ${address.port}`); } else { - console.error(`MCP Server running on streamable HTTP on port ${port}`); + console.error(`MCP Server running on streamable HTTP on port ${params.port}`); } }; diff --git a/packages/mcp-server/src/index.ts b/packages/mcp-server/src/index.ts index 0f6dd426..003a7655 100644 --- a/packages/mcp-server/src/index.ts +++ b/packages/mcp-server/src/index.ts @@ -18,10 +18,14 @@ async function main() { switch (options.transport) { case 'stdio': - await launchStdioServer(); + await launchStdioServer(options); break; case 'http': - await launchStreamableHTTPServer(options, options.port ?? options.socket); + await launchStreamableHTTPServer({ + mcpOptions: options, + debug: options.debug, + port: options.port ?? options.socket, + }); break; } } diff --git a/packages/mcp-server/src/methods.ts b/packages/mcp-server/src/methods.ts new file mode 100644 index 00000000..827dcf34 --- /dev/null +++ b/packages/mcp-server/src/methods.ts @@ -0,0 +1,364 @@ +import { McpOptions } from './options'; + +export type SdkMethod = { + clientCallName: string; + fullyQualifiedName: string; + httpMethod?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'query'; + httpPath?: string; +}; + +export const sdkMethods: SdkMethod[] = [ + { + clientCallName: 'client.accessTokens.create', + fullyQualifiedName: 'accessTokens.create', + httpMethod: 'post', + httpPath: '/auth/token', + }, + { + clientCallName: 'client.hris.company.retrieve', + fullyQualifiedName: 'hris.company.retrieve', + httpMethod: 'get', + httpPath: '/employer/company', + }, + { + clientCallName: 'client.hris.company.payStatementItem.list', + fullyQualifiedName: 'hris.company.payStatementItem.list', + httpMethod: 'get', + httpPath: '/employer/pay-statement-item', + }, + { + clientCallName: 'client.hris.company.payStatementItem.rules.create', + fullyQualifiedName: 'hris.company.payStatementItem.rules.create', + httpMethod: 'post', + httpPath: '/employer/pay-statement-item/rule', + }, + { + clientCallName: 'client.hris.company.payStatementItem.rules.update', + fullyQualifiedName: 'hris.company.payStatementItem.rules.update', + httpMethod: 'put', + httpPath: '/employer/pay-statement-item/rule/{rule_id}', + }, + { + clientCallName: 'client.hris.company.payStatementItem.rules.list', + fullyQualifiedName: 'hris.company.payStatementItem.rules.list', + httpMethod: 'get', + httpPath: '/employer/pay-statement-item/rule', + }, + { + clientCallName: 'client.hris.company.payStatementItem.rules.delete', + fullyQualifiedName: 'hris.company.payStatementItem.rules.delete', + httpMethod: 'delete', + httpPath: '/employer/pay-statement-item/rule/{rule_id}', + }, + { + clientCallName: 'client.hris.directory.list', + fullyQualifiedName: 'hris.directory.list', + httpMethod: 'get', + httpPath: '/employer/directory', + }, + { + clientCallName: 'client.hris.directory.listIndividuals', + fullyQualifiedName: 'hris.directory.listIndividuals', + }, + { + clientCallName: 'client.hris.individuals.retrieveMany', + fullyQualifiedName: 'hris.individuals.retrieveMany', + httpMethod: 'post', + httpPath: '/employer/individual', + }, + { + clientCallName: 'client.hris.employments.retrieveMany', + fullyQualifiedName: 'hris.employments.retrieveMany', + httpMethod: 'post', + httpPath: '/employer/employment', + }, + { + clientCallName: 'client.hris.payments.list', + fullyQualifiedName: 'hris.payments.list', + httpMethod: 'get', + httpPath: '/employer/payment', + }, + { + clientCallName: 'client.hris.payStatements.retrieveMany', + fullyQualifiedName: 'hris.payStatements.retrieveMany', + httpMethod: 'post', + httpPath: '/employer/pay-statement', + }, + { + clientCallName: 'client.hris.documents.list', + fullyQualifiedName: 'hris.documents.list', + httpMethod: 'get', + httpPath: '/employer/documents', + }, + { + clientCallName: 'client.hris.documents.retreive', + fullyQualifiedName: 'hris.documents.retreive', + httpMethod: 'get', + httpPath: '/employer/documents/{document_id}', + }, + { + clientCallName: 'client.hris.benefits.create', + fullyQualifiedName: 'hris.benefits.create', + httpMethod: 'post', + httpPath: '/employer/benefits', + }, + { + clientCallName: 'client.hris.benefits.retrieve', + fullyQualifiedName: 'hris.benefits.retrieve', + httpMethod: 'get', + httpPath: '/employer/benefits/{benefit_id}', + }, + { + clientCallName: 'client.hris.benefits.update', + fullyQualifiedName: 'hris.benefits.update', + httpMethod: 'post', + httpPath: '/employer/benefits/{benefit_id}', + }, + { + clientCallName: 'client.hris.benefits.list', + fullyQualifiedName: 'hris.benefits.list', + httpMethod: 'get', + httpPath: '/employer/benefits', + }, + { + clientCallName: 'client.hris.benefits.listSupportedBenefits', + fullyQualifiedName: 'hris.benefits.listSupportedBenefits', + httpMethod: 'get', + httpPath: '/employer/benefits/meta', + }, + { + clientCallName: 'client.hris.benefits.individuals.enrollMany', + fullyQualifiedName: 'hris.benefits.individuals.enrollMany', + httpMethod: 'post', + httpPath: '/employer/benefits/{benefit_id}/individuals', + }, + { + clientCallName: 'client.hris.benefits.individuals.enrolledIDs', + fullyQualifiedName: 'hris.benefits.individuals.enrolledIDs', + httpMethod: 'get', + httpPath: '/employer/benefits/{benefit_id}/enrolled', + }, + { + clientCallName: 'client.hris.benefits.individuals.retrieveManyBenefits', + fullyQualifiedName: 'hris.benefits.individuals.retrieveManyBenefits', + httpMethod: 'get', + httpPath: '/employer/benefits/{benefit_id}/individuals', + }, + { + clientCallName: 'client.hris.benefits.individuals.unenrollMany', + fullyQualifiedName: 'hris.benefits.individuals.unenrollMany', + httpMethod: 'delete', + httpPath: '/employer/benefits/{benefit_id}/individuals', + }, + { + clientCallName: 'client.providers.list', + fullyQualifiedName: 'providers.list', + httpMethod: 'get', + httpPath: '/providers', + }, + { + clientCallName: 'client.account.disconnect', + fullyQualifiedName: 'account.disconnect', + httpMethod: 'post', + httpPath: '/disconnect', + }, + { + clientCallName: 'client.account.introspect', + fullyQualifiedName: 'account.introspect', + httpMethod: 'get', + httpPath: '/introspect', + }, + { + clientCallName: 'client.requestForwarding.forward', + fullyQualifiedName: 'requestForwarding.forward', + httpMethod: 'post', + httpPath: '/forward', + }, + { + clientCallName: 'client.jobs.automated.create', + fullyQualifiedName: 'jobs.automated.create', + httpMethod: 'post', + httpPath: '/jobs/automated', + }, + { + clientCallName: 'client.jobs.automated.retrieve', + fullyQualifiedName: 'jobs.automated.retrieve', + httpMethod: 'get', + httpPath: '/jobs/automated/{job_id}', + }, + { + clientCallName: 'client.jobs.automated.list', + fullyQualifiedName: 'jobs.automated.list', + httpMethod: 'get', + httpPath: '/jobs/automated', + }, + { + clientCallName: 'client.jobs.manual.retrieve', + fullyQualifiedName: 'jobs.manual.retrieve', + httpMethod: 'get', + httpPath: '/jobs/manual/{job_id}', + }, + { + clientCallName: 'client.sandbox.connections.create', + fullyQualifiedName: 'sandbox.connections.create', + httpMethod: 'post', + httpPath: '/sandbox/connections', + }, + { + clientCallName: 'client.sandbox.connections.accounts.create', + fullyQualifiedName: 'sandbox.connections.accounts.create', + httpMethod: 'post', + httpPath: '/sandbox/connections/accounts', + }, + { + clientCallName: 'client.sandbox.connections.accounts.update', + fullyQualifiedName: 'sandbox.connections.accounts.update', + httpMethod: 'put', + httpPath: '/sandbox/connections/accounts', + }, + { + clientCallName: 'client.sandbox.company.update', + fullyQualifiedName: 'sandbox.company.update', + httpMethod: 'put', + httpPath: '/sandbox/company', + }, + { + clientCallName: 'client.sandbox.directory.create', + fullyQualifiedName: 'sandbox.directory.create', + httpMethod: 'post', + httpPath: '/sandbox/directory', + }, + { + clientCallName: 'client.sandbox.individual.update', + fullyQualifiedName: 'sandbox.individual.update', + httpMethod: 'put', + httpPath: '/sandbox/individual/{individual_id}', + }, + { + clientCallName: 'client.sandbox.employment.update', + fullyQualifiedName: 'sandbox.employment.update', + httpMethod: 'put', + httpPath: '/sandbox/employment/{individual_id}', + }, + { + clientCallName: 'client.sandbox.payment.create', + fullyQualifiedName: 'sandbox.payment.create', + httpMethod: 'post', + httpPath: '/sandbox/payment', + }, + { + clientCallName: 'client.sandbox.jobs.create', + fullyQualifiedName: 'sandbox.jobs.create', + httpMethod: 'post', + httpPath: '/sandbox/jobs', + }, + { + clientCallName: 'client.sandbox.jobs.configuration.retrieve', + fullyQualifiedName: 'sandbox.jobs.configuration.retrieve', + httpMethod: 'get', + httpPath: '/sandbox/jobs/configuration', + }, + { + clientCallName: 'client.sandbox.jobs.configuration.update', + fullyQualifiedName: 'sandbox.jobs.configuration.update', + httpMethod: 'put', + httpPath: '/sandbox/jobs/configuration', + }, + { + clientCallName: 'client.payroll.payGroups.retrieve', + fullyQualifiedName: 'payroll.payGroups.retrieve', + httpMethod: 'get', + httpPath: '/employer/pay-groups/{pay_group_id}', + }, + { + clientCallName: 'client.payroll.payGroups.list', + fullyQualifiedName: 'payroll.payGroups.list', + httpMethod: 'get', + httpPath: '/employer/pay-groups', + }, + { + clientCallName: 'client.connect.sessions.new', + fullyQualifiedName: 'connect.sessions.new', + httpMethod: 'post', + httpPath: '/connect/sessions', + }, + { + clientCallName: 'client.connect.sessions.reauthenticate', + fullyQualifiedName: 'connect.sessions.reauthenticate', + httpMethod: 'post', + httpPath: '/connect/sessions/reauthenticate', + }, +]; + +function allowedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined { + if (!options) { + return undefined; + } + + let allowedMethods: SdkMethod[]; + + if (options.codeAllowHttpGets || options.codeAllowedMethods) { + // Start with nothing allowed and then add into it from options + let allowedMethodsSet = new Set(); + + if (options.codeAllowHttpGets) { + // Add all methods that map to an HTTP GET + sdkMethods + .filter((method) => method.httpMethod === 'get') + .forEach((method) => allowedMethodsSet.add(method)); + } + + if (options.codeAllowedMethods) { + // Add all methods that match any of the allowed regexps + const allowedRegexps = options.codeAllowedMethods.map((pattern) => { + try { + return new RegExp(pattern); + } catch (e) { + throw new Error( + `Invalid regex pattern for allowed method: "${pattern}": ${e instanceof Error ? e.message : e}`, + ); + } + }); + + sdkMethods + .filter((method) => allowedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName))) + .forEach((method) => allowedMethodsSet.add(method)); + } + + allowedMethods = Array.from(allowedMethodsSet); + } else { + // Start with everything allowed + allowedMethods = [...sdkMethods]; + } + + if (options.codeBlockedMethods) { + // Filter down based on blocked regexps + const blockedRegexps = options.codeBlockedMethods.map((pattern) => { + try { + return new RegExp(pattern); + } catch (e) { + throw new Error( + `Invalid regex pattern for blocked method: "${pattern}": ${e instanceof Error ? e.message : e}`, + ); + } + }); + + allowedMethods = allowedMethods.filter( + (method) => !blockedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName)), + ); + } + + return allowedMethods; +} + +export function blockedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined { + const allowedMethods = allowedMethodsForCodeTool(options); + if (!allowedMethods) { + return undefined; + } + + const allowedSet = new Set(allowedMethods.map((method) => method.fullyQualifiedName)); + + // Return any methods that are not explicitly allowed + return sdkMethods.filter((method) => !allowedSet.has(method.fullyQualifiedName)); +} diff --git a/packages/mcp-server/src/options.ts b/packages/mcp-server/src/options.ts index c66ad8ce..92d1b074 100644 --- a/packages/mcp-server/src/options.ts +++ b/packages/mcp-server/src/options.ts @@ -4,6 +4,7 @@ import { hideBin } from 'yargs/helpers'; import z from 'zod'; export type CLIOptions = McpOptions & { + debug: boolean; transport: 'stdio' | 'http'; port: number | undefined; socket: string | undefined; @@ -11,36 +12,57 @@ export type CLIOptions = McpOptions & { export type McpOptions = { includeDocsTools?: boolean | undefined; + codeAllowHttpGets?: boolean | undefined; + codeAllowedMethods?: string[] | undefined; + codeBlockedMethods?: string[] | undefined; }; export function parseCLIOptions(): CLIOptions { const opts = yargs(hideBin(process.argv)) - .option('tools', { + .option('code-allow-http-gets', { + type: 'boolean', + description: + 'Allow all code tool methods that map to HTTP GET operations. If all code-allow-* flags are unset, then everything is allowed.', + }) + .option('code-allowed-methods', { type: 'string', array: true, - choices: ['code', 'docs'], - description: 'Use dynamic tools or all tools', + description: + 'Methods to explicitly allow for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.', }) - .option('no-tools', { + .option('code-blocked-methods', { type: 'string', array: true, - choices: ['code', 'docs'], - description: 'Do not use any dynamic or all tools', + description: + 'Methods to explicitly block for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.', }) - .option('transport', { + .option('debug', { type: 'boolean', description: 'Enable debug logging' }) + .option('no-tools', { type: 'string', - choices: ['stdio', 'http'], - default: 'stdio', - description: 'What transport to use; stdio for local servers or http for remote servers', + array: true, + choices: ['code', 'docs'], + description: 'Tools to explicitly disable', }) .option('port', { type: 'number', + default: 3000, description: 'Port to serve on if using http transport', }) - .option('socket', { + .option('socket', { type: 'string', description: 'Unix socket to serve on if using http transport' }) + .option('tools', { + type: 'string', + array: true, + choices: ['code', 'docs'], + description: 'Tools to explicitly enable', + }) + .option('transport', { type: 'string', - description: 'Unix socket to serve on if using http transport', + choices: ['stdio', 'http'], + default: 'stdio', + description: 'What transport to use; stdio for local servers or http for remote servers', }) + .env('MCP_SERVER') + .version(true) .help(); const argv = opts.parseSync(); @@ -56,6 +78,10 @@ export function parseCLIOptions(): CLIOptions { return { ...(includeDocsTools !== undefined && { includeDocsTools }), + debug: !!argv.debug, + codeAllowHttpGets: argv.codeAllowHttpGets, + codeAllowedMethods: argv.codeAllowedMethods, + codeBlockedMethods: argv.codeBlockedMethods, transport, port: argv.port, socket: argv.socket, diff --git a/packages/mcp-server/src/server.ts b/packages/mcp-server/src/server.ts index 065db351..26e54661 100644 --- a/packages/mcp-server/src/server.ts +++ b/packages/mcp-server/src/server.ts @@ -12,28 +12,65 @@ import Finch from '@tryfinch/finch-api'; import { codeTool } from './code-tool'; import docsSearchTool from './docs-search-tool'; import { McpOptions } from './options'; +import { blockedMethodsForCodeTool } from './methods'; import { HandlerFunction, McpTool } from './types'; export { McpOptions } from './options'; export { ClientOptions } from '@tryfinch/finch-api'; -export const newMcpServer = () => +async function getInstructions() { + // This API key is optional; providing it allows the server to fetch instructions for unreleased versions. + const stainlessAPIKey = readEnv('STAINLESS_API_KEY'); + const response = await fetch( + readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/finch', + { + method: 'GET', + headers: { ...(stainlessAPIKey && { Authorization: stainlessAPIKey }) }, + }, + ); + + let instructions: string | undefined; + if (!response.ok) { + console.warn( + 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...', + ); + + instructions = ` + This is the finch MCP server. You will use Code Mode to help the user perform + actions. You can use search_docs tool to learn about how to take action with this server. Then, + you will write TypeScript code using the execute tool take action. It is CRITICAL that you be + thoughtful and deliberate when executing code. Always try to entirely solve the problem in code + block: it can be as long as you need to get the job done! + `; + } + + instructions ??= ((await response.json()) as { instructions: string }).instructions; + instructions = ` + The current time in Unix timestamps is ${Date.now()}. + + ${instructions} + `; + + return instructions; +} + +export const newMcpServer = async () => new McpServer( { name: 'tryfinch_finch_api_api', - version: '9.0.0', + version: '9.1.0', + }, + { + instructions: await getInstructions(), + capabilities: { tools: {}, logging: {} }, }, - { capabilities: { tools: {}, logging: {} } }, ); -// Create server instance -export const server = newMcpServer(); - /** * Initializes the provided MCP Server with the given tools and handlers. * If not provided, the default client, tools and handlers will be used. */ -export function initMcpServer(params: { +export async function initMcpServer(params: { server: Server | McpServer; clientOptions?: ClientOptions; mcpOptions?: McpOptions; @@ -112,7 +149,11 @@ export function initMcpServer(params: { * Selects the tools to include in the MCP Server based on the provided options. */ export function selectTools(options?: McpOptions): McpTool[] { - const includedTools = [codeTool()]; + const includedTools = [ + codeTool({ + blockedMethods: blockedMethodsForCodeTool(options), + }), + ]; if (options?.includeDocsTools ?? true) { includedTools.push(docsSearchTool); } @@ -146,3 +187,10 @@ export const readEnvOrError = (env: string): string => { } return envValue; }; + +export const requireValue = (value: T | undefined, description: string): T => { + if (value === undefined) { + throw new Error(`Missing required value: ${description}`); + } + return value; +}; diff --git a/packages/mcp-server/src/stdio.ts b/packages/mcp-server/src/stdio.ts index f07696f3..57b99126 100644 --- a/packages/mcp-server/src/stdio.ts +++ b/packages/mcp-server/src/stdio.ts @@ -1,10 +1,11 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { McpOptions } from './options'; import { initMcpServer, newMcpServer } from './server'; -export const launchStdioServer = async () => { - const server = newMcpServer(); +export const launchStdioServer = async (mcpOptions: McpOptions) => { + const server = await newMcpServer(); - initMcpServer({ server }); + await initMcpServer({ server, mcpOptions }); const transport = new StdioServerTransport(); await server.connect(transport); diff --git a/packages/mcp-server/tsconfig.json b/packages/mcp-server/tsconfig.json index cded90d2..308897ae 100644 --- a/packages/mcp-server/tsconfig.json +++ b/packages/mcp-server/tsconfig.json @@ -2,8 +2,8 @@ "include": ["src", "tests", "examples"], "exclude": [], "compilerOptions": { - "target": "es2020", - "lib": ["es2020"], + "target": "es2022", + "lib": ["es2022"], "module": "commonjs", "moduleResolution": "node", "esModuleInterop": true, diff --git a/src/client.ts b/src/client.ts index a93f6575..46c8f7b2 100644 --- a/src/client.ts +++ b/src/client.ts @@ -555,7 +555,7 @@ export class Finch { loggerFor(this).info(`${responseInfo} - ${retryMessage}`); const errText = await response.text().catch((err: any) => castToError(err).message); - const errJSON = safeJSON(errText); + const errJSON = safeJSON(errText) as any; const errMessage = errJSON ? undefined : errText; loggerFor(this).debug( @@ -592,9 +592,14 @@ export class Finch { getAPIList = Pagination.AbstractPage>( path: string, Page: new (...args: any[]) => PageClass, - opts?: RequestOptions, + opts?: PromiseOrValue, ): Pagination.PagePromise { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); + return this.requestAPIList( + Page, + opts && 'then' in opts ? + opts.then((opts) => ({ method: 'get', path, ...opts })) + : { method: 'get', path, ...opts }, + ); } requestAPIList< @@ -602,7 +607,7 @@ export class Finch { PageClass extends Pagination.AbstractPage = Pagination.AbstractPage, >( Page: new (...args: ConstructorParameters) => PageClass, - options: FinalRequestOptions, + options: PromiseOrValue, ): Pagination.PagePromise { const request = this.makeRequest(options, null, undefined); return new Pagination.PagePromise(this as any as Finch, request, Page); @@ -615,9 +620,10 @@ export class Finch { controller: AbortController, ): Promise { const { signal, method, ...options } = init || {}; - if (signal) signal.addEventListener('abort', () => controller.abort()); + const abort = this._makeAbort(controller); + if (signal) signal.addEventListener('abort', abort, { once: true }); - const timeout = setTimeout(() => controller.abort(), ms); + const timeout = setTimeout(abort, ms); const isReadableBody = ((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) || @@ -785,6 +791,12 @@ export class Finch { return headers.values; } + private _makeAbort(controller: AbortController) { + // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure + // would capture all request options, and cause a memory leak. + return () => controller.abort(); + } + private buildBody({ options: { body, headers: rawHeaders } }: { options: FinalRequestOptions }): { bodyHeaders: HeadersLike; body: BodyInit | undefined; diff --git a/src/internal/parse.ts b/src/internal/parse.ts index 19d4f9db..c66b716b 100644 --- a/src/internal/parse.ts +++ b/src/internal/parse.ts @@ -29,6 +29,12 @@ export async function defaultParseResponse(client: Finch, props: APIResponseP const mediaType = contentType?.split(';')[0]?.trim(); const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); if (isJSON) { + const contentLength = response.headers.get('content-length'); + if (contentLength === '0') { + // if there is no content we can't do anything + return undefined as T; + } + const json = await response.json(); return json as T; } diff --git a/src/version.ts b/src/version.ts index b0a42860..024a40df 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = '9.0.0'; // x-release-please-version +export const VERSION = '9.1.0'; // x-release-please-version