diff --git a/.changeset/server-hosted-proxy.md b/.changeset/server-hosted-proxy.md new file mode 100644 index 0000000..3e74035 --- /dev/null +++ b/.changeset/server-hosted-proxy.md @@ -0,0 +1,11 @@ +--- +"@taskade/mcp-server": major +--- + +The package now forwards to the hosted Taskade MCP server by default. It connects to `https://www.taskade.com/mcp` with `TASKADE_API_KEY` as a Bearer token, and serves the hosted tools with their names, titles, annotations, schemas, results and errors. It also passes through the instructions, resources and prompts of the hosted server, and the notifications that a list changed. It does not pass through progress notifications, log messages, resource subscriptions, or the roots, sampling and elicitation capabilities of the client. The default mode needs a paid Taskade plan, as the hosted server does. At each start, the package writes one line about `--legacy` to stderr, and adds one sentence about it after the hosted instructions. + +A client config with `npx -y @taskade/mcp-server` and no version gets this version at the next start of the client. To keep the behavior of version 0.2.1 with no other change, use `@taskade/mcp-server@0.2.1`. + +This is a breaking change for a prompt, skill or script that names a tool of version 0.2, for example `workspacesGet` (now `list_spaces`) or `promptAgent` (now `prompt_agent`). Start the package with `--legacy`, or set `TASKADE_MCP_LEGACY=1`, to get the 66 tools of version 0.2 with the same names and the same API calls, on any plan. Legacy mode stays for one major version. + +A token that the hosted server refuses (HTTP 401) stops the package with one message. It tells how to create a token, states the plan rule and names `--legacy`. A network failure or an HTTP error at the start stops the package with one message that names `--legacy` too. In the default mode, every start failure, also a missing or short token, goes to stderr and is the error of the `initialize` request. Legacy mode writes it only to stderr, as before. The package removes the whitespace around the token, as version 0.2 did. A control character that is still in the token, for example a line break inside it, stops the package before any request. No message holds the token. `TASKADE_MCP_URL` points the package at a mock for a test. It accepts only `https://www.taskade.com`, or `127.0.0.1`, `localhost` and `[::1]`. diff --git a/Dockerfile b/Dockerfile index 20e7e64..ef36385 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM node:24.22.1-slim LABEL maintainer="Taskade " -LABEL description="Taskade MCP Server — AI tools for projects, tasks, agents, and webhooks via Model Context Protocol" +LABEL description="Taskade MCP Server: AI tools for projects, tasks and agents through the Model Context Protocol" LABEL org.opencontainers.image.source="https://github.com/taskade/mcp" LABEL org.opencontainers.image.licenses="MIT" diff --git a/README.md b/README.md index 5914e14..552af1d 100644 --- a/README.md +++ b/README.md @@ -95,10 +95,10 @@ Taskade runs the hosted server. This repository does not build it. Most people n | **Address or command** | `https://www.taskade.com/mcp` | `npx -y @taskade/mcp-server` | | **Sign-in** | OAuth in your browser. A client with no OAuth sends a personal access token in the `Authorization: Bearer` header. | A personal access token in the `TASKADE_API_KEY` environment variable | | **Install** | None | Node.js 18 or later. Your client starts the server on your computer over stdio. | -| **What it can do** | Read and change projects, tasks, custom fields and AI agents. Prompt an agent and attach knowledge to it. Edit the source of a Taskade Genesis app, and read who can use it. Run an automation that starts "When asked", and read its runs. Turn an automation on or off, and change the fields of its steps. Publish a new version of an app kit. | Read and change projects, tasks, custom fields, AI agents and media through REST API v1. Generate an agent from a prompt, turn on public agent access, delete media, prompt an agent, and manage the legacy webhook subscriptions. It cannot edit app source. | -| **Plan** | Every paid Taskade plan | Any plan. Each tool keeps the access rules of the API call that it makes. | -| **Use it when** | Your client connects to remote servers. This is the case for most clients. | You need a REST API v1 operation that the hosted server does not expose. | -| **Tool reference** | [Hosted tools](#hosted-tools) | [Local package tools](#local-package-tools) | +| **What it can do** | Read and change projects, tasks, custom fields and AI agents. Prompt an agent and attach knowledge to it. Edit the source of a Taskade Genesis app, and read who can use it. Run an automation that starts "When asked", and read its runs. Turn an automation on or off, and change the fields of its steps. Publish a new version of an app kit. | By default, the same as the hosted server: the package forwards each request to `https://www.taskade.com/mcp`. With `--legacy`, the tools of version 0.2: read and change projects, tasks, custom fields, AI agents and media through REST API v1, generate an agent from a prompt, turn on public agent access, delete media, prompt an agent, and manage the legacy webhook subscriptions. | +| **Plan** | Every paid Taskade plan | By default, every paid Taskade plan, as the hosted server. With `--legacy`, any plan. Each legacy tool keeps the access rules of the API call that it makes. | +| **Use it when** | Your client connects to remote servers. This is the case for most clients. | Your client runs only local stdio servers, or you need a REST API v1 operation of legacy mode. | +| **Tool reference** | [Hosted tools](#hosted-tools) | [Hosted tools](#hosted-tools). With `--legacy`: [Local package tools](#local-package-tools) | To call another MCP server from Taskade, use the [MCP Client connector](https://www.taskade.com/learn/connect/mcp-client-integration) in an automation. It runs on every plan. Help to choose: [Which Taskade MCP do I want?](https://www.taskade.com/docs/mcp/which-mcp) @@ -432,7 +432,7 @@ Clients (read only): | `401` with `{"error":"Unauthorized"}` before you sign in | This is normal. Without a token, the server answers `401` with a `WWW-Authenticate` header that names its sign-in metadata. Your client reads it and opens the Taskade sign-in. | Finish the sign-in. If no sign-in page opens, update the client, or send a personal access token (see [other clients](#other-clients-and-servers-api-token)). | | `401` with `{"error":"Unauthorized"}` from a client that sends a token | The server found no token. It reads a token only from the `Authorization` header, in the form `Bearer `. It ignores a token in another header, a token without `Bearer`, and a token in the URL. | Send `Authorization: Bearer `. | | `401` with `{"error":"Invalid or expired token"}` | The server read the token and refused it. The token is wrong or revoked. | Create a new token in [Settings > API](https://www.taskade.com/settings/api), and update the header. | -| `list_spaces` returns no workspaces, or `MCP access is not available on this workspace's current plan.` | The workspace is on the Free plan. The hosted tools need a paid plan, and `list_spaces` hides a Free workspace. The list also comes in pages, and one page can be empty while more pages remain. | Page until `hasNextPage` is `false`. Upgrade the workspace at [taskade.com/pricing](https://www.taskade.com/pricing?utm_source=github&utm_medium=readme&utm_campaign=taskade-mcp), or pick a paid workspace. | +| `list_spaces` returns no workspaces, or `MCP access is not available on this workspace's current plan.` | The workspace is on the Free plan. The hosted tools need a paid plan, and `list_spaces` hides a Free workspace. The list also comes in pages, and one page can be empty while more pages remain. | Page until `hasNextPage` is `false`. Upgrade the workspace at [taskade.com/pricing](https://www.taskade.com/pricing?utm_source=github&utm_medium=readme&utm_campaign=taskade-mcp), or pick a paid workspace. With the local package, you can also start it with `--legacy`. The tools of version 0.2 work with an API key on any plan. | | The client runs only local stdio servers | The hosted server uses Streamable HTTP. | Connect through the [`mcp-remote` bridge](#other-clients-and-servers-api-token), or use the [local package](#local-package-stdio). | | The agent does not see the Taskade tools after an install | The client has not loaded the new server, or the sign-in is not done. | Restart the client, or open its MCP list: `/mcp` in Claude Code, the MCP settings in Cursor, or start the server from `mcp.json` in VS Code. Then sign in. `npx @taskade/cli doctor` shows which clients have a `taskade` entry. | | `Access denied: you are not a member of this space.` | Your account is not a member of the workspace. | Make sure that the workspace ID is correct, or ask for an invitation. | @@ -440,6 +440,11 @@ Clients (read only): | The OAuth sign-in starts again and again | The browser is signed in to another Taskade account, or the stored credential is old. | Sign in to the right Taskade account in your browser. Remove the Taskade server from the client, then add it again. | | Claude shows "Authorization with the MCP server failed" | The connector sign-in failed. | Remove the connector, add it again, and sign in to the correct Taskade account. | | The local package stops with `TASKADE_API_KEY environment variable is not set.` or `TASKADE_API_KEY appears to be invalid (too short).` | The client did not pass a token to the local package. | Create a token in [Settings > API](https://www.taskade.com/settings/api), and set `TASKADE_API_KEY` in the `env` block of the client config. | +| The local package stops with `The Taskade MCP server refused TASKADE_API_KEY (HTTP 401).` | By default, the local package forwards to the hosted server, and the hosted server refused the token. The token is wrong or revoked. | Create a new token in [Settings > API](https://www.taskade.com/settings/api), and update `TASKADE_API_KEY`. On the Free plan, start the package with `--legacy`. | +| The local package stops with `The local package cannot reach the Taskade MCP server` | In the default mode, the package connects to the hosted server when it starts. The network is down, or the server answered with an HTTP error. | Check the network, then restart the server from your client. Legacy mode (`--legacy`) starts without the hosted server. | +| The local package stops with `TASKADE_API_KEY holds a control character` | The package removes the spaces, tabs and line breaks around the token. A control character is still in the token, for example a line break inside it, often from a copy and paste. | Copy the token again, and paste it on one line. | + +When the local package stops at its start in the default mode, it sends the message as the error of the `initialize` request, and writes it to stderr. This includes a missing or short token. In legacy mode, the message goes only to stderr, as in version 0.2. Many clients show only a failed state. The full message is then in the server log of the client, for example the MCP log of Claude Desktop or the Output panel of VS Code. The full list of tool errors is in [Troubleshooting](https://www.taskade.com/docs/mcp/hosted-mcp#troubleshooting) of the hosted guide. @@ -457,7 +462,7 @@ For a check in a terminal, the CLI mode prints the tool list as JSON and exits: npx @modelcontextprotocol/inspector --cli -e TASKADE_API_KEY=your-api-key-here --method tools/list -- npx -y @taskade/mcp-server ``` -The tool list does not call the Taskade API. To test the token, call a tool such as `workspacesGet`. The Inspector stores the `-e` values in the keychain of your system, or in a file when no keychain is available. See its README. +By default, the package connects to the hosted server when it starts. A wrong token stops it with the 401 message in [Failures and fixes](#failures-and-fixes). With `--legacy` after `@taskade/mcp-server`, the tool list does not call the Taskade API. To test the token in legacy mode, call a tool such as `workspacesGet`. The Inspector stores the `-e` values in the keychain of your system, or in a file when no keychain is available. See its README. If the problem continues, open an [issue](https://github.com/taskade/mcp/issues) or email [support@taskade.com](mailto:support@taskade.com). @@ -465,7 +470,52 @@ If the problem continues, open an [issue](https://github.com/taskade/mcp/issues) ## Local package (stdio) -Use the local package when you need a REST API v1 operation that the hosted server does not expose. Examples are generate an agent from a prompt, turn on public agent access, delete media, and the legacy webhook subscription tools (`subscribeWebhook`, `unsubscribeWebhook`). The package runs on your computer with `npx` and needs Node.js 18 or later. It calls the Taskade public API over the network with a personal access token. It does not edit Taskade Genesis app source. Guide: [Workspace MCP](https://www.taskade.com/docs/mcp/workspace-mcp). +The local package runs on your computer with `npx` and needs Node.js 18 or later. It reads a personal access token from `TASKADE_API_KEY`. Guide: [Workspace MCP](https://www.taskade.com/docs/mcp/workspace-mcp). + +The package has two modes: + +| Mode | Start | What it serves | Plan | +|---|---|---|---| +| Default | `npx -y @taskade/mcp-server` | The [hosted tools](#hosted-tools). The package connects to `https://www.taskade.com/mcp` with your token as a Bearer token, and forwards each request. Tool names, schemas, results and errors are the ones of the hosted server. | Every paid Taskade plan. The hosted server does not work on the Free plan. | +| Legacy | `npx -y @taskade/mcp-server --legacy`, or `TASKADE_MCP_LEGACY=1` | The [local package tools](#local-package-tools) of version 0.2, which call REST API v1 and v2. | Any plan | + +Use legacy mode when you need a REST API v1 operation that the hosted server does not expose. Examples are generate an agent from a prompt, turn on public agent access, delete media, and the legacy webhook subscription tools (`subscribeWebhook`, `unsubscribeWebhook`). Use it also on the Free plan. Legacy mode stays for one major version. Then it goes away. + +At each start in the default mode, the package writes one line about `--legacy` to stderr. It also adds one sentence about `--legacy` after the instructions of the hosted server, so the model can tell you about legacy mode. + +What the default mode passes through, and what it does not: + +- The package answers `initialize` and `ping` itself. It sends every other request of your client to the hosted server, for example `tools/list`, `tools/call`, `resources/read` and `prompts/get`. The answer comes back unchanged. +- A cancel from your client cancels the request on the hosted server. +- From the hosted server, only the notifications that a tool, resource or prompt list changed reach your client. Progress notifications, log messages and resource updates do not. +- The package offers no resource subscription. It does not send the roots, sampling or elicitation capabilities of your client to the hosted server, and it does not send a roots change of your client. + +### Migrate from version 0.2 + +Version 0.2 served the legacy tools by default. A client config with `npx -y @taskade/mcp-server` and no version gets version 1.0.0 at the next start of the client. Version 1.0.0 serves the hosted names by default. To keep the behavior of version 0.2.1 with no other change, put `@taskade/mcp-server@0.2.1` in `args`. + +A prompt, skill or script that names a tool of version 0.2 needs the hosted name, or `--legacy`: + +| Version 0.2 tool | Hosted tool | +|---|---| +| `workspacesGet` | `list_spaces` | +| `workspaceFoldersGet` | `list_folders` | +| `projectGet` | `get_project` | +| `renameProject` | `rename_project` | +| `listTasks` | `list_tasks` | +| `createTask` | `create_task` | +| `taskPut` | `update_task` | +| `setTaskFieldValue` | `set_task_field_value` | +| `folderCreateAgent` | `create_agent` | +| `promptAgent` | `prompt_agent` | + +The arguments of a hosted tool can differ from the arguments of the old tool. Your client reads the schema of each tool after it connects. + +To start legacy mode from a client config, add `--legacy` to `args`. The other steps below do not change: + +```json +"args": ["-y", "@taskade/mcp-server", "--legacy"] +``` ### 1. Get your API key @@ -591,7 +641,7 @@ The npm package runs over stdio only. For a client that connects over HTTP, use ## Local package tools -The local package has its own tool names. They map to the Taskade public API v1 and v2. The [Workspace MCP](https://www.taskade.com/docs/mcp/workspace-mcp#full-tool-reference) guide has the same list. +The local package serves these tools in legacy mode only (`--legacy` or `TASKADE_MCP_LEGACY=1`). They map to the Taskade public API v1 and v2. In the default mode, the package serves the [hosted tools](#hosted-tools). The [Workspace MCP](https://www.taskade.com/docs/mcp/workspace-mcp#full-tool-reference) guide has the same list. ### Workspaces @@ -752,7 +802,7 @@ Taskade MCP includes **AI agent management** (create, train, deploy agents), **k ## Agent Recipes -The recipes use the tool names of the [local package](#local-package-tools). The hosted server has its own names (see [Hosted tools](#hosted-tools)). +The recipes use the tool names of the [local package in legacy mode](#local-package-tools). The hosted server and the default mode of the local package have other names (see [Hosted tools](#hosted-tools)).
Recipe 1: Daily Standup Summarizer @@ -949,7 +999,7 @@ See [open issues](https://github.com/taskade/mcp/issues) for planned features an - **Hosted server.** Taskade runs it on `www.taskade.com`. It reads and writes only the workspaces that your Taskade account can access and that are on a paid plan. The server does not read your chat history with the AI client. `prompt_agent` runs a Taskade agent, which can use its own tools, for example web search. - **Agent plugin.** The plugin holds skills (text files) and the address of the hosted server. It runs no code of its own. The `taskade-publish-app` skill writes its backup of an app to a local folder (`./taskade-backup/` unless you name another one). The `taskade-repo-to-project` skill reads a local code repository and sends no source code to Taskade. -- **Local package.** Your API token authorizes the server to call the Taskade public API (`https://www.taskade.com/api/v1` and `https://www.taskade.com/api/v2`) on your behalf. The package sends your data to no other service. Keep the token in an environment variable, and never commit it. +- **Local package.** By default, the package sends your API token and each request to the hosted server (`https://www.taskade.com/mcp`). In legacy mode, your API token authorizes the server to call the Taskade public API (`https://www.taskade.com/api/v1` and `https://www.taskade.com/api/v2`) on your behalf. The package sends your data to no other service. Keep the token in an environment variable, and never commit it. - **Privacy policy:** [taskade.com/privacy](https://www.taskade.com/privacy). **Terms:** [taskade.com/terms](https://www.taskade.com/terms). - **Security and vulnerability reports:** see [SECURITY.md](./SECURITY.md). diff --git a/packages/server/README.md b/packages/server/README.md index 914c083..bc87035 100644 --- a/packages/server/README.md +++ b/packages/server/README.md @@ -1,8 +1,12 @@ # Taskade MCP Server — Workspace MCP (`@taskade/mcp-server`) -The **Workspace MCP** server connects an MCP client that runs local stdio servers (Claude Desktop, Claude Code, Cursor, VS Code, Windsurf) to your Taskade workspace. Its tools read and write your projects, tasks, AI agents, media and custom fields through the Taskade public API. +The **Workspace MCP** server connects an MCP client that runs local stdio servers (Claude Desktop, Claude Code, Cursor, VS Code, Windsurf) to your Taskade workspace. -Most people need the hosted server instead: `https://www.taskade.com/mcp`. It needs no install, signs in with OAuth, and can edit Taskade Genesis app source. See [Hosted server or local package](https://github.com/taskade/mcp#hosted-server-or-local-package). +By default, the package connects to the hosted Taskade MCP server, `https://www.taskade.com/mcp`, with your token as a Bearer token. It serves the hosted tools with their names, and forwards each request. The hosted server works on every paid Taskade plan. It does not work on the Free plan. + +With `--legacy` (or `TASKADE_MCP_LEGACY=1`), the package serves the tools of version 0.2 instead. They read and write your projects, tasks, AI agents, media and custom fields through the Taskade public API v1 and v2, on any plan. Legacy mode stays for one major version. + +A client that connects to remote servers needs no install: it can use `https://www.taskade.com/mcp` directly, with OAuth. See [Hosted server or local package](https://github.com/taskade/mcp#hosted-server-or-local-package). > 📖 **Full documentation lives in the canonical sources — this package README is intentionally a stub to avoid drift.** @@ -18,6 +22,16 @@ TASKADE_API_KEY="your-api-key-here" npx -y @taskade/mcp-server You need Node.js 18 or later and a Taskade personal access token. Create the token at [https://www.taskade.com/settings/api](https://www.taskade.com/settings/api). +Legacy mode: + +```sh +TASKADE_API_KEY="your-api-key-here" npx -y @taskade/mcp-server --legacy +``` + +A client config with `npx -y @taskade/mcp-server` and no version gets version 1.0.0 at the next start of the client. To keep the behavior of version 0.2.1 with no other change, use `@taskade/mcp-server@0.2.1`. + +To test the package against a local mock, set `TASKADE_MCP_URL`. It accepts only an address on `https://www.taskade.com`, `127.0.0.1`, `localhost` or `[::1]`, because the package sends your token there. + To list the tools and call them, run the package in the [MCP Inspector](https://github.com/modelcontextprotocol/inspector): ```sh diff --git a/packages/server/src/__snapshots__/legacy-tool-names.json b/packages/server/src/__snapshots__/legacy-tool-names.json new file mode 100644 index 0000000..1feeb65 --- /dev/null +++ b/packages/server/src/__snapshots__/legacy-tool-names.json @@ -0,0 +1,68 @@ +[ + "workspaceCreateProject", + "workspacesGet", + "workspaceFoldersGet", + "projectGet", + "projectComplete", + "projectRestore", + "projectCopy", + "projectCreate", + "projectFromTemplate", + "projectMembersGet", + "projectFieldsGet", + "projectShareLinkGet", + "projectShareLinkEnable", + "projectBlocksGet", + "projectTasksGet", + "taskGet", + "taskDelete", + "taskPut", + "taskComplete", + "taskUncomplete", + "taskCreate", + "taskMove", + "taskAssigneesGet", + "taskPutAssignees", + "taskDeleteAssignees", + "taskGetDate", + "taskDeleteDate", + "taskPutDate", + "taskNoteGet", + "taskNotePut", + "taskNoteDelete", + "taskFieldsValueGet", + "taskFieldValueGet", + "taskFieldValueDelete", + "taskFieldValuePut", + "folderProjectsGet", + "folderAgentGenerate", + "folderCreateAgent", + "folderAgentGet", + "mediasGet", + "folderProjectTemplatesGet", + "meProjectsGet", + "agentPublicAccessEnable", + "agentGet", + "deleteAgent", + "agentUpdate", + "agentPublicGet", + "agentPublicUpdate", + "agentKnowledgeProjectCreate", + "agentKnowledgeMediaCreate", + "agentKnowledgeProjectRemove", + "agentKnowledgeMediaRemove", + "agentConvosGet", + "agentConvoGet", + "mediaGet", + "mediaDelete", + "publicAgentGet", + "promptAgent", + "listConversations", + "getConversation", + "listTasks", + "renameProject", + "createTask", + "setTaskFieldValue", + "subscribeWebhook", + "unsubscribeWebhook" +] diff --git a/packages/server/src/cli.ts b/packages/server/src/cli.ts index 3f09c8e..eb4b34b 100644 --- a/packages/server/src/cli.ts +++ b/packages/server/src/cli.ts @@ -1,50 +1,125 @@ +import { inspect } from 'node:util'; + import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; +import { ErrorCode, isJSONRPCRequest } from '@modelcontextprotocol/sdk/types.js'; +import { + createProxyServer, + hostedServerTransport, + hostedServerUrl, + isLegacyMode, + LEGACY_NOTE, +} from './proxy'; import { TaskadeMCPServer } from './server'; -function validateAccessToken(token: string | undefined): string { +// Legacy mode prints the message and exits, as version 0.2 did. +function exitWith(message: string): never { + console.error(message); + process.exit(1); +} + +// Removes the whitespace around the key. `fail` gets the message for a missing or short key. +function validateAccessToken(token: string | undefined, fail: (message: string) => never): string { if (!token) { - console.error( + fail( 'ERROR: TASKADE_API_KEY environment variable is not set.\n\n' + 'To fix this:\n' + '1. Generate a Personal Access Token at: https://www.taskade.com/settings/api\n' + '2. Set the environment variable:\n' + ' export TASKADE_API_KEY="your_token_here"\n', ); - process.exit(1); } const trimmedToken = token.trim(); if (trimmedToken.length === 0) { - console.error('ERROR: TASKADE_API_KEY is empty. Please provide a valid token.'); - process.exit(1); + fail('ERROR: TASKADE_API_KEY is empty. Please provide a valid token.'); } if (trimmedToken.length < 10) { - console.error( + fail( 'ERROR: TASKADE_API_KEY appears to be invalid (too short).\n' + 'Please verify your token at: https://www.taskade.com/settings/api', ); - process.exit(1); } return trimmedToken; } +// Most clients show only a failed state when the server exits, and keep stderr in a log. A +// client shows the error of its initialize request, so the message goes there too. +async function answerWithError(text: string): Promise { + process.exitCode = 1; + const transport = new StdioServerTransport(); + transport.onmessage = (request) => { + if (isJSONRPCRequest(request)) { + void transport + .send({ + jsonrpc: '2.0', + id: request.id, + error: { code: ErrorCode.InternalError, message: text }, + }) + .then(() => transport.close()); + } + }; + await transport.start(); +} + +// Cuts the key out of a text, so that no unexpected error shows it. +function withoutKey(text: string): string { + const key = process.env.TASKADE_API_KEY?.trim(); + return key ? text.split(key).join('') : text; +} + +function throwError(message: string): never { + throw new Error(message); +} + async function main() { - const accessToken = validateAccessToken(process.env.TASKADE_API_KEY); + // Legacy mode: the tools that the package generates from the Taskade API v1 and v2. + if (isLegacyMode(process.argv.slice(2), process.env)) { + const accessToken = validateAccessToken(process.env.TASKADE_API_KEY, exitWith); + const server = new TaskadeMCPServer({ + accessToken, + }); + const transport = new StdioServerTransport(); + await server.connect(transport); - const server = new TaskadeMCPServer({ - accessToken, - }); - const transport = new StdioServerTransport(); - await server.connect(transport); + console.error('Taskade MCP Server running on stdio'); + return; + } + + // Default mode: forward the MCP session to the hosted server. Every failure before the + // stdio connection goes to stderr and to the initialize request of the client. + console.error(LEGACY_NOTE); + let url; + let server; + try { + const accessToken = validateAccessToken(process.env.TASKADE_API_KEY, throwError); + url = hostedServerUrl(process.env.TASKADE_MCP_URL); + server = await createProxyServer(hostedServerTransport(url, accessToken)); + } catch (error) { + const message = + error instanceof Error && error.message.startsWith('ERROR: ') + ? error.message + : `ERROR: The local package could not start: ${withoutKey(String(error))}`; + console.error(message); + await answerWithError(message); + return; + } + // The connection to the hosted server keeps the process alive. Close it when the client + // closes stdin, so the process ends as in legacy mode. + process.stdin.on('end', () => void server.close()); + await server.connect(new StdioServerTransport()); - console.error('Taskade MCP Server running on stdio'); + console.error(`Taskade MCP Server running on stdio, connected to ${url.origin}${url.pathname}`); } main().catch((error) => { - console.error('Fatal error in main():', error); + if (error instanceof Error && error.message.startsWith('ERROR: ')) { + console.error(error.message); + } else { + console.error('Fatal error in main():', withoutKey(inspect(error))); + } process.exit(1); }); diff --git a/packages/server/src/proxy.test.ts b/packages/server/src/proxy.test.ts new file mode 100644 index 0000000..6495005 --- /dev/null +++ b/packages/server/src/proxy.test.ts @@ -0,0 +1,677 @@ +import { spawn } from 'node:child_process'; +import { createServer, type IncomingHttpHeaders, type Server as HttpServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { fileURLToPath } from 'node:url'; + +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { McpError, ResultSchema } from '@modelcontextprotocol/sdk/types.js'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { + createProxyServer, + HOSTED_MCP_URL, + hostedServerTransport, + hostedServerUrl, + isLegacyMode, + LEGACY_NOTE, +} from './proxy'; + +// A fake token. Tests never read TASKADE_API_KEY from the environment. +const TOKEN = 'proxy-test-token-0123456789'; +// A key with a line break in it. Node puts a bad header value into its error message. +const KEY_WITH_LINE_BREAK = 'line-break-key-0123456789\nsecond-line-9876543210'; +const MOCK_INSTRUCTIONS = 'Mock hosted server. Call list_spaces first.'; + +const MOCK_TOOLS = [ + { + name: 'list_spaces', + title: 'List workspaces', + description: 'List the workspaces of the account.', + inputSchema: { + type: 'object', + properties: { page: { type: 'integer', description: 'Page number' } }, + }, + outputSchema: { type: 'object', properties: { items: { type: 'array' } } }, + annotations: { title: 'List workspaces', readOnlyHint: true, openWorldHint: false }, + _meta: { 'example.com/extra': 'kept' }, + }, + { + name: 'delete_task', + title: 'Delete a task', + inputSchema: { type: 'object', properties: { taskId: { type: 'string' } } }, + annotations: { destructiveHint: true }, + }, +]; + +// An in-process stand-in for the hosted server, with one tool of each kind, one resource and +// one prompt. It uses the low-level Server, so each field reaches the wire as written here. +function createMockHostedServer() { + const server = new Server( + { name: 'mock-hosted', version: '9.9.9' }, + { + capabilities: { tools: { listChanged: true }, resources: {}, prompts: {} }, + instructions: MOCK_INSTRUCTIONS, + }, + ); + // The mock answers each method in one handler. A typed handler for each method makes + // TypeScript fail with "excessively deep" on the zod 3.25 types. + server.fallbackRequestHandler = async ({ method, params = {} }) => { + const args = (params.arguments ?? {}) as Record; + switch (method) { + case 'tools/list': + return { tools: MOCK_TOOLS }; + case 'tools/call': + return params.name === 'list_spaces' + ? { + content: [{ type: 'text', text: `spaces page ${args.page ?? 1}` }], + structuredContent: { items: [{ id: 's1', name: 'Marketing' }] }, + } + : { + isError: true, + content: [{ type: 'text', text: `Task ${args.taskId} was not found.` }], + }; + case 'resources/list': + return { resources: [{ uri: 'taskade://getting-started', name: 'getting-started' }] }; + case 'resources/read': + if (params.uri !== 'taskade://getting-started') { + throw new McpError(-32002, `Resource ${params.uri} not found`); + } + return { contents: [{ uri: params.uri, text: '# Getting started' }] }; + case 'prompts/list': + return { + prompts: [{ name: 'weekly_review', arguments: [{ name: 'project', required: true }] }], + }; + case 'prompts/get': + return { + messages: [{ role: 'user', content: { type: 'text', text: `Review ${args.project}` } }], + }; + default: + throw new McpError(-32601, 'Method not found'); + } + }; + return server; +} + +type Mock = { + url: URL; + headers: IncomingHttpHeaders[]; + // Answers every request with this HTTP status. `undefined` serves the mock again. + setStatus: (status: number | undefined) => void; + // Answers initialize with a protocol version that no client supports. + setOldProtocol: (value: boolean) => void; + close: () => Promise; +}; + +async function startMock(): Promise { + const headers: IncomingHttpHeaders[] = []; + let forcedStatus: number | undefined; + let oldProtocol = false; + const http: HttpServer = createServer(async (req, res) => { + headers.push(req.headers); + if (oldProtocol) { + let body = ''; + for await (const chunk of req) { + body += chunk; + } + const { id } = JSON.parse(body); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end( + JSON.stringify({ + jsonrpc: '2.0', + id, + result: { + protocolVersion: '1999-01-01', + capabilities: {}, + serverInfo: { name: 'old', version: '0' }, + }, + }), + ); + return; + } + if (forcedStatus != null && forcedStatus !== 401) { + res.writeHead(forcedStatus).end('Service Unavailable'); + return; + } + if (forcedStatus === 401 || req.headers.authorization !== `Bearer ${TOKEN}`) { + res.writeHead(401, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ error: 'Invalid or expired token' })); + return; + } + if (req.method !== 'POST') { + res.writeHead(405).end(); + return; + } + // Stateless mode: one server and one transport for each request. + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true, + }); + res.on('close', () => void transport.close()); + await createMockHostedServer().connect(transport); + await transport.handleRequest(req, res); + }); + await new Promise((resolve) => http.listen(0, '127.0.0.1', resolve)); + const { port } = http.address() as AddressInfo; + return { + url: new URL(`http://127.0.0.1:${port}/mcp`), + headers, + setStatus: (status) => { + forcedStatus = status; + }, + setOldProtocol: (value) => { + oldProtocol = value; + }, + close: () => + new Promise((resolve) => { + http.closeAllConnections(); + http.close(() => resolve()); + }), + }; +} + +async function connectClient(server: Server): Promise { + const client = new Client({ name: 'test-client', version: '0.0.0' }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + return client; +} + +describe('the stdio proxy to the hosted server', () => { + let mock: Mock; + let stderr: string[]; + const clients: Client[] = []; + + beforeAll(async () => { + mock = await startMock(); + }); + + afterAll(async () => { + await mock.close(); + }); + + beforeEach(() => { + mock.headers.length = 0; + mock.setStatus(undefined); + stderr = []; + vi.spyOn(console, 'error').mockImplementation((...args) => { + stderr.push(args.map(String).join(' ')); + }); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await Promise.all(clients.splice(0).map((client) => client.close())); + expect(stderr.join('\n')).not.toContain(TOKEN); + }); + + async function startProxy() { + const proxy = await connectClient( + await createProxyServer(hostedServerTransport(mock.url, TOKEN)), + ); + // A client that connects to the mock directly, to compare with the proxy. + const direct = new Client({ name: 'direct', version: '0.0.0' }); + await direct.connect( + new StreamableHTTPClientTransport(mock.url, { + requestInit: { headers: { Authorization: `Bearer ${TOKEN}`, 'User-Agent': 'direct-test' } }, + }), + ); + // Closing the proxy client also closes the connection of the proxy to the mock. + clients.push(proxy, direct); + return { proxy, direct }; + } + + it('passes the instructions and the capabilities of the hosted server through', async () => { + const { proxy, direct } = await startProxy(); + + // The hosted instructions come first and unchanged, then one sentence about legacy mode. + expect(proxy.getInstructions()).toBe(`${MOCK_INSTRUCTIONS}\n\n${LEGACY_NOTE}`); + expect(LEGACY_NOTE).toContain('--legacy'); + expect(LEGACY_NOTE).toContain('any plan'); + expect(proxy.getServerCapabilities()).toEqual(direct.getServerCapabilities()); + expect(proxy.getServerCapabilities()).toEqual({ + tools: { listChanged: true }, + resources: {}, + prompts: {}, + }); + }); + + it('lists the tools of the hosted server unchanged', async () => { + const { proxy, direct } = await startProxy(); + + const viaProxy = await proxy.request({ method: 'tools/list', params: {} }, ResultSchema); + const viaDirect = await direct.request({ method: 'tools/list', params: {} }, ResultSchema); + + expect(viaProxy).toEqual(viaDirect); + expect(viaProxy.tools).toEqual(MOCK_TOOLS); + }); + + it('forwards a tool call and returns its result unchanged', async () => { + const { proxy, direct } = await startProxy(); + const params = { name: 'list_spaces', arguments: { page: 2 } }; + + const viaProxy = await proxy.request({ method: 'tools/call', params }, ResultSchema); + const viaDirect = await direct.request({ method: 'tools/call', params }, ResultSchema); + + expect(viaProxy).toEqual(viaDirect); + expect(viaProxy).toEqual({ + content: [{ type: 'text', text: 'spaces page 2' }], + structuredContent: { items: [{ id: 's1', name: 'Marketing' }] }, + }); + }); + + it('forwards a tool error result and a protocol error with their text', async () => { + const { proxy, direct } = await startProxy(); + + const toolError = await proxy.callTool({ name: 'delete_task', arguments: { taskId: 't9' } }); + expect(toolError).toEqual({ + isError: true, + content: [{ type: 'text', text: 'Task t9 was not found.' }], + }); + + const readMissing = (client: Client) => + client.readResource({ uri: 'taskade://missing' }).catch((error: unknown) => error); + const viaProxy = await readMissing(proxy); + const viaDirect = await readMissing(direct); + expect(viaProxy).toMatchObject({ code: (viaDirect as { code: number }).code }); + // The text equals the text of a direct connection. The proxy adds no second prefix. + expect((viaProxy as Error).message).toBe((viaDirect as Error).message); + expect((viaProxy as Error).message).toContain('Resource taskade://missing not found'); + }); + + it('forwards resources and prompts', async () => { + const { proxy } = await startProxy(); + + const { resources } = await proxy.listResources(); + expect(resources.map((resource) => resource.uri)).toEqual(['taskade://getting-started']); + const read = await proxy.readResource({ uri: 'taskade://getting-started' }); + expect(read.contents).toEqual([ + { uri: 'taskade://getting-started', text: '# Getting started' }, + ]); + + const { prompts } = await proxy.listPrompts(); + expect(prompts.map((prompt) => prompt.name)).toEqual(['weekly_review']); + const prompt = await proxy.getPrompt({ name: 'weekly_review', arguments: { project: 'Q4' } }); + expect(prompt.messages).toEqual([ + { role: 'user', content: { type: 'text', text: 'Review Q4' } }, + ]); + }); + + it('forwards a tool list change of the hosted server', async () => { + // A stateless mock cannot push a notification, so this test links the mock in memory. + const hostedServer = createMockHostedServer(); + const [toProxy, toHosted] = InMemoryTransport.createLinkedPair(); + await hostedServer.connect(toHosted); + const proxy = await connectClient(await createProxyServer(toProxy)); + clients.push(proxy); + const changed = new Promise((resolve) => { + proxy.fallbackNotificationHandler = async (notification) => resolve(notification.method); + }); + + await hostedServer.sendToolListChanged(); + + await expect(changed).resolves.toBe('notifications/tools/list_changed'); + }); + + it('sends the token as a Bearer header and names the package on every request', async () => { + const { proxy } = await startProxy(); + mock.headers.length = 0; + + await proxy.listTools(); + + // The direct client of the comparison tests sends its own User-Agent. Skip its requests. + const fromProxy = mock.headers.filter((header) => header['user-agent'] !== 'direct-test'); + expect(fromProxy.length).toBeGreaterThan(0); + for (const header of fromProxy) { + expect(header.authorization).toBe(`Bearer ${TOKEN}`); + expect(header['user-agent']).toMatch(/^taskade-mcp-server\/\d+\.\d+\.\d+/); + } + }); + + it('turns a 401 at startup into one clear message without the token', async () => { + mock.setStatus(401); + + const error = await createProxyServer(hostedServerTransport(mock.url, TOKEN)).catch( + (e: unknown) => e, + ); + + expect(error).toBeInstanceOf(Error); + const message = (error as Error).message; + expect(message).toContain('https://www.taskade.com/settings/api'); + expect(message).toContain('paid Taskade plan'); + expect(message).toContain('--legacy'); + expect(message).toContain('TASKADE_MCP_LEGACY=1'); + expect(message).not.toContain(TOKEN); + expect(mock.headers).toHaveLength(1); + }); + + it.each([ + { cause: 'a 503 answer', status: 503 }, + { cause: 'a closed port', status: undefined }, + ])('turns $cause at startup into one clear message', async ({ status }) => { + mock.setStatus(status); + // A loopback port with no server behind it. + const closed = await startMock(); + await closed.close(); + const url = status == null ? closed.url : mock.url; + + const error = await createProxyServer(hostedServerTransport(url, TOKEN)).catch( + (e: unknown) => e, + ); + + const message = (error as Error).message; + expect(message).toMatch(/^ERROR: The local package cannot reach the Taskade MCP server/); + expect(message).toContain('--legacy'); + expect(message).not.toContain('TypeError'); + expect(message).not.toContain(TOKEN); + }); + + it('refuses a key with a control character, and never shows the key', async () => { + const error = await Promise.resolve() + .then(() => createProxyServer(hostedServerTransport(mock.url, KEY_WITH_LINE_BREAK))) + .catch((e: unknown) => e); + + const message = (error as Error).message; + expect(message).toContain('TASKADE_API_KEY'); + expect(message).toContain('control character'); + for (const part of KEY_WITH_LINE_BREAK.split('\n')) { + expect(message).not.toContain(part); + } + expect(mock.headers).toHaveLength(0); + }); + + it.each([ + { where: 'a NUL at the start', key: `\u0000${TOKEN}` }, + { where: 'a NUL at the end', key: `${TOKEN}\u0000` }, + { where: 'a control character at the end', key: `${TOKEN}\u0001` }, + ])('refuses a key with $where, because trimming keeps it', async ({ key }) => { + // The CLI trims the key first. String.prototype.trim keeps these characters. + expect(key.trim()).toBe(key); + expect(() => hostedServerTransport(mock.url, key.trim())).toThrow('control character'); + expect(mock.headers).toHaveLength(0); + }); + + it('turns a 401 during a session into the same message', async () => { + const { proxy } = await startProxy(); + mock.setStatus(401); + + const error = await proxy.listTools().catch((e: unknown) => e); + + expect(String((error as Error).message)).toContain('https://www.taskade.com/settings/api'); + expect(String((error as Error).message)).not.toContain(TOKEN); + expect(stderr.join('\n')).toContain('--legacy'); + }); +}); + +describe('the mode and the address of the server', () => { + it('starts legacy mode only with --legacy or TASKADE_MCP_LEGACY', () => { + expect(isLegacyMode([], {})).toBe(false); + expect(isLegacyMode(['--legacy'], {})).toBe(true); + expect(isLegacyMode([], { TASKADE_MCP_LEGACY: '1' })).toBe(true); + expect(isLegacyMode([], { TASKADE_MCP_LEGACY: 'true' })).toBe(true); + expect(isLegacyMode([], { TASKADE_MCP_LEGACY: '0' })).toBe(false); + expect(isLegacyMode([], { TASKADE_MCP_LEGACY: '' })).toBe(false); + }); + + it('uses the hosted server, or a loopback address for a test', () => { + expect(hostedServerUrl(undefined).href).toBe(HOSTED_MCP_URL); + expect(hostedServerUrl('').href).toBe(HOSTED_MCP_URL); + expect(hostedServerUrl('https://www.taskade.com/mcp').href).toBe(HOSTED_MCP_URL); + expect(hostedServerUrl('http://127.0.0.1:4000/mcp').href).toBe('http://127.0.0.1:4000/mcp'); + expect(hostedServerUrl('http://localhost:4000/mcp').href).toBe('http://localhost:4000/mcp'); + expect(hostedServerUrl('http://[::1]:4000/mcp').href).toBe('http://[::1]:4000/mcp'); + }); + + // The key goes to this address, and a project config file can set it. So no other host. + it('refuses every other address, and does not echo it', () => { + for (const value of [ + 'https://example.com/mcp', + 'https://www.taskade.com.example.com/mcp', + 'https://taskade.com/mcp', + 'http://www.taskade.com/mcp', + 'https://www.taskade.com:8443/mcp', + 'https://user:pass@www.taskade.com/mcp', + 'https://www.taskade.com@example.com/mcp', + 'http://127.0.0.1@example.com/mcp', + 'http://localhost.example.com/mcp', + 'ftp://127.0.0.1/mcp', + 'not a url', + ]) { + expect(() => hostedServerUrl(value), value).toThrow('TASKADE_MCP_URL'); + } + // The message does not echo the address, so it shows no user name or password. + expect(() => hostedServerUrl('https://user:secret-pass@www.taskade.com/mcp')).toThrow( + /^(?!.*secret-pass)/s, + ); + }); +}); + +// These tests start the command line entry point in a child process, the way an MCP client does. +describe('the command line entry point', () => { + const cli = fileURLToPath(new URL('./cli.ts', import.meta.url)); + let mock: Mock; + + beforeAll(async () => { + mock = await startMock(); + }); + + afterAll(async () => { + await mock.close(); + }); + + // Sends initialize and tools/list over stdin, then closes stdin and waits for the exit. + function runCli(args: string[], env: NodeJS.ProcessEnv) { + return new Promise<{ code: number | null; stdout: string; stderr: string }>( + (resolve, reject) => { + const child = spawn(process.execPath, ['--import', 'tsx', cli, ...args], { + env: { PATH: process.env.PATH ?? '', ...env }, + stdio: ['pipe', 'pipe', 'pipe'], + }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { + stdout += chunk; + if (stdout.includes('"id":2')) { + child.stdin.end(); + } + }); + child.stderr.on('data', (chunk) => (stderr += chunk)); + child.on('error', reject); + child.on('exit', (code) => resolve({ code, stdout, stderr })); + const send = (message: object) => child.stdin.write(`${JSON.stringify(message)}\n`); + send({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-06-18', + capabilities: {}, + clientInfo: { name: 'cli-test', version: '0.0.0' }, + }, + }); + send({ jsonrpc: '2.0', method: 'notifications/initialized' }); + send({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }); + }, + ); + } + + function toolNames(stdout: string): string[] { + const response = stdout + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)) + .find((message) => message.id === 2); + return response.result.tools.map((tool: { name: string }) => tool.name); + } + + it('serves the tools of the hosted server by default, and exits when stdin closes', async () => { + const { code, stdout, stderr } = await runCli([], { + TASKADE_API_KEY: TOKEN, + TASKADE_MCP_URL: mock.url.href, + }); + + expect(toolNames(stdout)).toEqual(['list_spaces', 'delete_task']); + expect(code).toBe(0); + // Every start in the default mode names the legacy switch, on one line. + expect(stderr.split('\n')).toContain(LEGACY_NOTE); + expect(stderr).not.toContain(TOKEN); + }, 30_000); + + it('exits with the clear message when the hosted server answers 401', async () => { + const { code, stdout, stderr } = await runCli([], { + TASKADE_API_KEY: 'wrong-token-0123456789', + TASKADE_MCP_URL: mock.url.href, + }); + + expect(code).toBe(1); + expect(stderr).toContain('https://www.taskade.com/settings/api'); + expect(stderr).toContain('--legacy'); + // The client also gets the message as the error of its initialize request. + const answer = JSON.parse(stdout.trim().split('\n')[0]); + expect(answer).toMatchObject({ jsonrpc: '2.0', id: 1, error: { code: -32603 } }); + expect(answer.error.message).toContain('https://www.taskade.com/settings/api'); + expect(answer.error.message).toContain('--legacy'); + expect(`${stdout}${stderr}`).not.toContain('wrong-token-0123456789'); + }, 30_000); + + it('exits with a clear message when the hosted server cannot be reached', async () => { + const closed = await startMock(); + await closed.close(); + + const { code, stdout, stderr } = await runCli([], { + TASKADE_API_KEY: TOKEN, + TASKADE_MCP_URL: closed.url.href, + }); + + expect(code).toBe(1); + expect(stderr).toContain('cannot reach the Taskade MCP server'); + expect(stderr).not.toContain('TypeError'); + expect(JSON.parse(stdout.trim().split('\n')[0]).error.message).toContain('--legacy'); + }, 30_000); + + it('never prints a key that holds a line break', async () => { + const { code, stdout, stderr } = await runCli([], { + TASKADE_API_KEY: KEY_WITH_LINE_BREAK, + TASKADE_MCP_URL: mock.url.href, + }); + + expect(code).toBe(1); + expect(stderr).toContain('control character'); + for (const part of KEY_WITH_LINE_BREAK.split('\n')) { + expect(`${stdout}${stderr}`).not.toContain(part); + } + }, 30_000); + + function initializeError(stdout: string): string { + const answer = JSON.parse(stdout.trim().split('\n')[0]); + expect(answer).toMatchObject({ jsonrpc: '2.0', id: 1, error: { code: -32603 } }); + return answer.error.message; + } + + it('removes the whitespace around the key', async () => { + const { code, stdout } = await runCli([], { + TASKADE_API_KEY: ` \t${TOKEN}\r\n`, + TASKADE_MCP_URL: mock.url.href, + }); + + expect(code).toBe(0); + expect(toolNames(stdout)).toEqual(['list_spaces', 'delete_task']); + }, 30_000); + + it('refuses a control character at the end of the key that is not whitespace', async () => { + const { code, stdout, stderr } = await runCli([], { + TASKADE_API_KEY: `${TOKEN}\u0001`, + TASKADE_MCP_URL: mock.url.href, + }); + + expect(code).toBe(1); + expect(initializeError(stdout)).toContain('control character'); + expect(`${stdout}${stderr}`).not.toContain(TOKEN); + }, 30_000); + + it.each([ + { problem: 'no key', key: undefined, text: 'TASKADE_API_KEY environment variable is not set' }, + { problem: 'a key of spaces', key: ' ', text: 'TASKADE_API_KEY is empty' }, + { problem: 'a short key', key: 'short', text: 'too short' }, + ])( + 'answers initialize with the error for $problem in the default mode', + async ({ key, text }) => { + const { code, stdout, stderr } = await runCli([], { + ...(key == null ? {} : { TASKADE_API_KEY: key }), + TASKADE_MCP_URL: mock.url.href, + }); + + expect(code).toBe(1); + expect(stderr).toContain(text); + expect(initializeError(stdout)).toContain(text); + }, + 30_000, + ); + + it('answers initialize with an unexpected start error, without the key', async () => { + mock.setOldProtocol(true); + try { + const { code, stdout, stderr } = await runCli([], { + TASKADE_API_KEY: TOKEN, + TASKADE_MCP_URL: mock.url.href, + }); + + expect(code).toBe(1); + expect(initializeError(stdout)).toMatch( + /^ERROR: The local package could not start: .*1999-01-01/, + ); + expect(`${stdout}${stderr}`).not.toContain(TOKEN); + } finally { + mock.setOldProtocol(false); + } + }, 30_000); + + it('keeps the start of version 0.2.1 for a missing key in legacy mode', async () => { + const { code, stdout, stderr } = await runCli(['--legacy'], {}); + + expect(code).toBe(1); + expect(stdout).toBe(''); + expect(stderr).toBe( + 'ERROR: TASKADE_API_KEY environment variable is not set.\n\n' + + 'To fix this:\n' + + '1. Generate a Personal Access Token at: https://www.taskade.com/settings/api\n' + + '2. Set the environment variable:\n' + + ' export TASKADE_API_KEY="your_token_here"\n\n', + ); + }, 30_000); + + it.each([ + { mode: '--legacy', args: ['--legacy'], env: {} }, + { mode: 'TASKADE_MCP_LEGACY=1', args: [], env: { TASKADE_MCP_LEGACY: '1' } }, + ])( + 'serves the same 66 generated tools as version 0.2.1 with $mode', + async ({ args, env }) => { + // The URL points at the mock: legacy mode must not call it. + mock.headers.length = 0; + const { code, stdout } = await runCli(args, { + TASKADE_API_KEY: TOKEN, + TASKADE_MCP_URL: mock.url.href, + ...env, + }); + + expect(code).toBe(0); + // Legacy mode sends no instructions, as version 0.2.1 did. + const initialize = stdout + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)) + .find((message) => message.id === 1); + expect(initialize.result.serverInfo.name).toBe('taskade'); + expect(initialize.result).not.toHaveProperty('instructions'); + // The file holds the tool list of version 0.2.1, in order. Legacy mode must not change it. + await expect(`${JSON.stringify(toolNames(stdout), null, 2)}\n`).toMatchFileSnapshot( + './__snapshots__/legacy-tool-names.json', + ); + expect(mock.headers).toHaveLength(0); + }, + 30_000, + ); +}); diff --git a/packages/server/src/proxy.ts b/packages/server/src/proxy.ts new file mode 100644 index 0000000..bacc6b3 --- /dev/null +++ b/packages/server/src/proxy.ts @@ -0,0 +1,200 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { + StreamableHTTPClientTransport, + StreamableHTTPError, +} from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; +import { + McpError, + ResultSchema, + type ServerCapabilities, + type ServerNotification, + type ServerResult, +} from '@modelcontextprotocol/sdk/types.js'; + +import { version } from '../package.json'; +import { USER_AGENT } from './server'; + +export const HOSTED_MCP_URL = 'https://www.taskade.com/mcp'; + +// The client of the proxy owns the timeout. Its cancel reaches the hosted server through the +// abort signal, so this limit only ends a request that nobody cancels. +const FORWARD_TIMEOUT_MS = 15 * 60 * 1000; + +export function isLegacyMode(argv: string[], env: NodeJS.ProcessEnv): boolean { + const flag = (env.TASKADE_MCP_LEGACY ?? '').trim().toLowerCase(); + return argv.includes('--legacy') || flag === '1' || flag === 'true'; +} + +// The local package can also start with --legacy. The first sentence names the package, because +// the model reads it after the instructions of the hosted server. +export const LEGACY_NOTE = + 'The local package @taskade/mcp-server can also start with --legacy. ' + + 'That mode serves the tools of version 0.2, which work with a Taskade API key on any plan.'; + +const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '[::1]']; + +// TASKADE_MCP_URL exists to test the proxy against a mock. The key goes to this address, and a +// project config file can set it, so it accepts only the hosted origin or a loopback host. +export function hostedServerUrl(value: string | undefined): URL { + const text = value?.trim() || HOSTED_MCP_URL; + let url: URL; + try { + url = new URL(text); + } catch { + throw new Error('ERROR: TASKADE_MCP_URL is not a valid URL.'); + } + const hosted = url.origin === new URL(HOSTED_MCP_URL).origin; + const loopback = + LOOPBACK_HOSTS.includes(url.hostname) && + (url.protocol === 'http:' || url.protocol === 'https:'); + if ((hosted || loopback) && url.username === '' && url.password === '') { + return url; + } + throw new Error( + 'ERROR: TASKADE_MCP_URL must be on https://www.taskade.com, or on 127.0.0.1, localhost or [::1] for a test.', + ); +} + +const UNAUTHORIZED_MESSAGE = + 'ERROR: The Taskade MCP server refused TASKADE_API_KEY (HTTP 401).\n\n' + + 'To fix this:\n' + + '1. Create a personal access token at: https://www.taskade.com/settings/api\n' + + '2. Set it in the TASKADE_API_KEY environment variable.\n\n' + + 'The hosted server works on every paid Taskade plan. It does not work on the Free plan.\n' + + 'To use the tools of version 0.2 with any plan, start the package with --legacy,\n' + + 'or set TASKADE_MCP_LEGACY=1.\n'; + +function unreachableMessage(error: StreamableHTTPError | TypeError): string { + const cause = (error as { cause?: { code?: unknown } }).cause?.code; + const detail = + error instanceof StreamableHTTPError + ? `HTTP ${error.code}` + : typeof cause === 'string' + ? cause + : 'network error'; + return ( + `ERROR: The local package cannot reach the Taskade MCP server (${detail}).\n\n` + + 'Check the network connection, then restart the server from your MCP client.\n' + + 'Legacy mode works without the hosted server: start the package with --legacy,\n' + + 'or set TASKADE_MCP_LEGACY=1.\n' + ); +} + +// An error from the hosted server keeps its code and its text. McpError adds an "MCP error" +// prefix to the text. The prefix comes off here, because the client of the proxy adds it again. +function forwardedError(error: unknown): Error { + if (error instanceof StreamableHTTPError && error.code === 401) { + return new Error(UNAUTHORIZED_MESSAGE); + } + if (error instanceof McpError) { + const prefix = `MCP error ${error.code}: `; + const text = error.message.startsWith(prefix) + ? error.message.slice(prefix.length) + : error.message; + return Object.assign(new Error(text), { code: error.code, data: error.data }); + } + return error instanceof Error ? new Error(error.message) : new Error(String(error)); +} + +export function hostedServerTransport(url: URL, accessToken: string): Transport { + // The CLI removes the whitespace around the key first. A control character that is still in + // the key (inside it, or a NUL at an edge) stops the package here. Node puts an invalid + // header value, with the key, into its error message, so this check comes first. + const controlCharacter = [...accessToken].some((c) => c < ' ' || c === '\u007f'); + if (controlCharacter) { + throw new Error( + 'ERROR: TASKADE_API_KEY holds a control character, for example a line break inside it. ' + + 'Copy the token again from https://www.taskade.com/settings/api.', + ); + } + return new StreamableHTTPClientTransport(url, { + requestInit: { + headers: { Authorization: `Bearer ${accessToken}`, 'User-Agent': USER_AGENT }, + }, + }); +} + +// Connects to the hosted server, then returns a server for the stdio client. +// - It answers `initialize` and `ping` itself, with the instructions of the hosted server and +// LEGACY_NOTE after them. +// - It sends every other request of its client to the hosted server. Names, titles, +// annotations, schemas, results and errors pass through unchanged. A cancel of the client +// cancels the request on the hosted server. +// - It sends the tools, resources and prompts list_changed notifications of the hosted server +// to its client. It drops the other notifications of the hosted server (progress, log +// messages, resource updates) and every notification of its client except a cancel. +// - It does not offer the roots, sampling or elicitation capabilities of its client to the +// hosted server. +// Its close also closes the connection to the hosted server. +export async function createProxyServer(hostedTransport: Transport): Promise { + const upstream = new Client({ name: 'taskade-mcp-server', version }); + try { + await upstream.connect(hostedTransport); + } catch (error) { + if (error instanceof StreamableHTTPError && error.code === 401) { + throw new Error(UNAUTHORIZED_MESSAGE); + } + // An HTTP error answer, or a network failure ("fetch failed"). + if (error instanceof StreamableHTTPError || error instanceof TypeError) { + throw new Error(unreachableMessage(error)); + } + throw error; + } + + const hosted = upstream.getServerCapabilities() ?? {}; + const capabilities: ServerCapabilities = {}; + if (hosted.tools) { + capabilities.tools = hosted.tools; + } + // The proxy forwards no resource subscription, so it does not offer one. + if (hosted.resources) { + capabilities.resources = { listChanged: hosted.resources.listChanged }; + } + if (hosted.prompts) { + capabilities.prompts = hosted.prompts; + } + + const server = new Server( + { name: 'taskade', version }, + { + capabilities, + instructions: [upstream.getInstructions(), LEGACY_NOTE].filter(Boolean).join('\n\n'), + }, + ); + + // TypeScript cannot resolve the generic type of request() with the zod 3.25 types + // ("excessively deep"). This plain signature is enough to forward a request. + const request = upstream.request.bind(upstream) as unknown as ( + request: { method: string; params?: Record }, + resultSchema: typeof ResultSchema, + options: { signal: AbortSignal; timeout: number }, + ) => Promise; + + let reportedUnauthorized = false; + server.fallbackRequestHandler = async ({ method, params }, extra) => { + try { + return await request({ method, params }, ResultSchema, { + signal: extra.signal, + timeout: FORWARD_TIMEOUT_MS, + }); + } catch (error) { + const forwarded = forwardedError(error); + // A token that stops working during a session gets the same message, once. + if (forwarded.message === UNAUTHORIZED_MESSAGE && !reportedUnauthorized) { + reportedUnauthorized = true; + console.error(UNAUTHORIZED_MESSAGE); + } + throw forwarded; + } + }; + upstream.fallbackNotificationHandler = async (notification) => { + if (notification.method.endsWith('/list_changed')) { + await server.notification(notification as ServerNotification); + } + }; + server.onclose = () => void upstream.close(); + + return server; +} diff --git a/packages/server/src/server.ts b/packages/server/src/server.ts index f916626..4f273d0 100644 --- a/packages/server/src/server.ts +++ b/packages/server/src/server.ts @@ -8,7 +8,7 @@ import { setupToolsV2 } from './tools.v2.generated'; // Every API request names this package and its version. With this header, Taskade can measure // the usage of the package and debug its requests. The build inlines `version` from // package.json into bin/cli.mjs. -const USER_AGENT = `taskade-mcp-server/${version}`; +export const USER_AGENT = `taskade-mcp-server/${version}`; type TaskadeServerOpts = { accessToken: string; diff --git a/smithery.yaml b/smithery.yaml index 0a7e512..3aec4e0 100644 --- a/smithery.yaml +++ b/smithery.yaml @@ -10,5 +10,10 @@ startCommand: type: string title: "Taskade API Key" description: "Your Taskade API key. Get it from Taskade Settings > API." + legacy: + type: boolean + default: false + title: "Legacy mode" + description: "Serve the tools of version 0.2, which work with an API key on any Taskade plan. The default mode serves the tools of the hosted Taskade MCP server, which needs a paid plan." commandFunction: |- - (config) => ({ command: 'npx', args: ['-y', '@taskade/mcp-server'], env: { TASKADE_API_KEY: config.apiKey } }) + (config) => ({ command: 'npx', args: ['-y', '@taskade/mcp-server', ...(config.legacy ? ['--legacy'] : [])], env: { TASKADE_API_KEY: config.apiKey } })