diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88a2b8b..2f71480 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,6 +9,10 @@ on: jobs: test: runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: ['20', '22', '24'] steps: - name: Checkout code @@ -17,14 +21,15 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '20' + node-version: ${{ matrix.node }} cache: 'npm' - name: Install dependencies run: npm ci - - name: Run tests - run: npm test + - name: Build and run unit and protocol integration tests + run: npm run check - - name: Build project - run: npm run build + - name: Check coverage + if: matrix.node == '24' + run: npm run test:coverage diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 6b1be88..1f39933 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -30,14 +30,14 @@ cd mcps **安装依赖:** ```bash -npm install +npm ci ``` --- ## 本地开发 -**开发模式(使用 ts-node 直接运行):** +**开发模式(使用 ts-node ESM loader,子进程继承 loader):** ```bash npm run dev -- # 例如 @@ -94,6 +94,10 @@ npm run test:coverage - 保持测试覆盖率在合理水平 - **TypeScript 编译必须无错误** +测试包含配置文件保护、真实 CLI 参数解析、daemon 路由、连接池并发与关闭,以及真实 SDK 服务的 stdio、Streamable HTTP、旧 SSE、新旧协议协商、OAuth 和多轮输入请求。测试启动前会编译 CLI,子进程测试使用独立配置目录和随机端口,结束时关闭自己创建的进程。 + +协议支持范围和可选能力见 [MCP_SUPPORT.md](docs/MCP_SUPPORT.md)。不要用测试数量代替行为验证,也不要给客户端宣告尚未实现的 sampling、roots 或扩展能力。 + --- ## 提交规范 diff --git a/README.md b/README.md index 7157339..74997fe 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,19 @@ A powerful command-line interface for managing and interacting with [Model Conte - 🔍 **Tool Filtering**: Filter tools by keywords with simple mode - 🚨 **Verbose Logging**: Optional detailed logging for debugging +## MCP protocol support + +Supports MCP **2026-07-28** with SDK v2, automatic legacy negotiation, resources, prompts, completion, manual multi-round-trip elicitation and OAuth client credentials. See [the support matrix](docs/MCP_SUPPORT.md) for tested behavior and optional host features. + +```bash +mcps discover my-server +mcps resources my-server +mcps read my-server resource://document +mcps prompts my-server +mcps prompt my-server welcome name=Taipei +mcps call my-server my-tool --output-json +``` + ## Installation ```bash @@ -292,27 +305,32 @@ You can change the storage location by setting the `MCPS_CONFIG_DIR` environment Configuration file example: ```json { - "servers": [ - { - "name": "fetch", - "type": "stdio", + "daemonTimeout": 20000, + "mcpServers": { + "fetch": { "command": "uvx", - "args": ["mcp-server-fetch"] + "args": ["mcp-server-fetch"], + "protocolVersion": "auto" }, - { - "name": "my-server", - "type": "stdio", + "my-server": { "command": "node", "args": ["./build/index.js"], - "env": { - "API_KEY": "${API_KEY}" - }, + "cwd": "/workspace/my-server", + "env": { "API_KEY": "${API_KEY}" }, "disabled": false + }, + "remote": { + "type": "http", + "url": "https://mcp.example.com/mcp", + "headers": { "Authorization": "Bearer ${MCP_TOKEN}" } } - ] + } } ``` + +Use `mcps config path` and `mcps config validate` to inspect configuration. Root options and extension fields are preserved. Writes are atomic and refuse to overwrite malformed or invalid configuration. The legacy `servers` array is unsupported; convert it to the `mcpServers` map before modifying it. + ## Environment Variables - `MCPS_CONFIG_DIR`: Configuration file directory (default: `~/.mcps`) diff --git a/README.zh.md b/README.zh.md index 5159931..cb94ac4 100644 --- a/README.zh.md +++ b/README.zh.md @@ -15,6 +15,19 @@ - 🚨 **详细日志**:可选的详细日志模式,方便调试 - ✅ **自动化测试**:完整的测试套件,确保代码质量 +## MCP 协议支持 + +已支持 **MCP 2026-07-28** 与官方 SDK v2,包括新版自动协商和旧版回退、资源、提示词、参数补全、手动多轮 elicitation 与 OAuth 客户端凭据认证。已验证范围及可选能力见 [支持矩阵](docs/MCP_SUPPORT.md)。 + +```bash +mcps discover my-server +mcps resources my-server +mcps read my-server resource://document +mcps prompts my-server +mcps prompt my-server welcome name=Taipei +mcps call my-server my-tool --output-json +``` + ## 安装 ```bash @@ -293,27 +306,32 @@ mcps call my-server createUser --json params.json 配置文件示例: ```json { - "servers": [ - { - "name": "fetch", - "type": "stdio", + "daemonTimeout": 20000, + "mcpServers": { + "fetch": { "command": "uvx", - "args": ["mcp-server-fetch"] + "args": ["mcp-server-fetch"], + "protocolVersion": "auto" }, - { - "name": "my-server", - "type": "stdio", + "my-server": { "command": "node", "args": ["./build/index.js"], - "env": { - "API_KEY": "${API_KEY}" - }, + "cwd": "/workspace/my-server", + "env": { "API_KEY": "${API_KEY}" }, "disabled": false + }, + "remote": { + "type": "http", + "url": "https://mcp.example.com/mcp", + "headers": { "Authorization": "Bearer ${MCP_TOKEN}" } } - ] + } } ``` + +使用 `mcps config path` 查看实际路径,用 `mcps config validate` 检查配置。写入保留根字段和扩展字段,采用原子替换;配置损坏或条目无效时拒绝覆盖。旧 `servers` 数组格式不受支持,应先转换为以服务名为键的 `mcpServers` 对象。 + ## 环境变量 - `MCPS_CONFIG_DIR`: 配置文件目录(默认:`~/.mcps`) diff --git a/docs/MCP_SUPPORT.md b/docs/MCP_SUPPORT.md new file mode 100644 index 0000000..1cba207 --- /dev/null +++ b/docs/MCP_SUPPORT.md @@ -0,0 +1,82 @@ +# MCP 支持范围 + +本次升级以 2026-10-07 核实的最新稳定规范 **2026-07-28** 为目标,运行时使用官方 `@modelcontextprotocol/client 2.3.1`。v1 SDK 仅作为开发依赖,用于和真实旧服务进行互操作测试。 + +规范和迁移依据: + +- [MCP 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28) +- [官方变更说明](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2026-07-28/changelog.mdx) +- [SDK v2 迁移指南](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/migration/upgrade-to-v2.md) +- [新版协议启用指南](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/docs/migration/support-2026-07-28.md) + +## 已实现并验证 + +| 能力 | 行为与验证 | +| --- | --- | +| 新版协商与发现 | 默认 `protocolVersion: "auto"`,使用 `server/discover` 选择新版;`mcps discover ` 展示协商版本、能力和发现结果 | +| 旧版兼容 | 自动回退到 SDK 支持的旧协议;真实 v1 SDK 服务验证了 2025-11-25;也验证了旧 SSE,显式类型优先于 URL 路径推断 | +| 新版 stdio / Streamable HTTP | HTTP 抓取验证每次请求都携带版本与客户端能力,无 initialize、无 Session-Id;认证错误不会被当作旧版证据 | +| 工具与分页 | `tools/list` 自动汇总所有页;使用 SDK 缓存和失效机制,去掉独立的永久工具缓存 | +| JSON Schema / 结果内容 | SDK 验证 outputSchema;支持数组等任意 JSON structuredContent,以及 audio、resource_link、嵌入资源和 metadata;`--output-json` 保留完整结果 | +| 资源和模板 | `mcps resources `、`--templates`、`mcps read ` | +| 提示词与补全 | `mcps prompts `、`mcps prompt [KEY=VALUE...]`、`mcps complete --json ''` | +| 新版变更订阅 | SDK 自动使用 `subscriptions/listen` 接收工具、资源及提示词列表变更;HTTP 抓取验证订阅请求,stdio 验证新增工具可发现 | +| 新版多轮输入 | 将 input_required 完整交给 CLI 用户,通过 inputResponses 和不透明 requestState 显式续接;不会自动同意表单或 URL 请求 | +| 认证 | headers 支持环境变量占位符;OAuth client_credentials 使用 SDK 发现元数据、获取并复用令牌,校验注册 issuer;通过本地 OAuth 服务测试 | +| 关闭和重连 | SDK 管理 stdio 子进程;测试确认重连后旧 PID 已退出;连接池去重并发请求并阻止重置后的连接复活 | + +`auto` 的 stdio 探测使用 SDK 的临时兄弟进程,默认等待至多 2 秒;daemon 复用连接,不会为每次工具调用重复探测。对已知旧服务可配置 `protocolVersion: "legacy"` 跳过探测。配置 `"2026-07-28"` 则强制新版,连接旧服务会明确失败。旧 SSE 只用于兼容旧协议,不能强制新版。 + +## CLI 配置和错误处理 + +配置格式为 `{ "mcpServers": { "": { ... } } }`。README 中原先的旧 `servers` 数组示例已修正。 + +- `mcps config path` / `mcps config validate`:查看有效路径并检查完整配置。 +- 根级 daemonTimeout 的单位为毫秒;MCPS_DAEMON_TIMEOUT 环境变量的单位为秒,优先级更高。 +- add / update 支持 type、cwd、env、headers、protocolVersion 和 disabled;update 支持 `--enabled` 恢复。 +- env/header 按第一个等号拆分,保留空值和后续等号。参数错误返回非零退出码。 +- 根级与服务扩展字段在读写过程中保留。损坏 JSON、旧格式或无效现有条目会阻止写入,原始文件不变。 +- 写入通过临时文件原子替换,并用独占锁阻止并发覆盖。进程被强制终止时可能留下 `mcp.json.lock`;先确认没有写入进程,再移除遗留锁。 +- 修改已连接服务后执行 `mcps restart `。 + +多轮示例: + +```bash +mcps call server approval_tool --output-json +# 退出码 2,返回 inputRequests 和 requestState;根据用户决定填写响应。 +mcps call server approval_tool --output-json \ + --request-state '' \ + --input-responses '{"approval":{"action":"accept","content":{"approved":true}}}' +``` + +退出码:0 表示完成,1 表示参数、连接、协议或工具级错误,2 表示需要输入后续接。工具返回 isError 时不会提示成功。资源和提示词命令也支持 `--input-responses` / `--request-state`。 + +OAuth 客户端凭据示例,只保存密钥变量名: + +```bash +mcps add remote --type http --url https://mcp.example.com/mcp \ + --oauth-client-id my-client \ + --oauth-client-secret-env MCP_CLIENT_SECRET \ + --oauth-issuer https://auth.example.com \ + --oauth-scope 'mcp:read' +``` + +## 可选能力与后续范围 + +支持最新协议版本不等于实现所有可选 host 能力或官方扩展: + +- 浏览器 OAuth authorization_code 登录、客户端 ID 元数据文档注册、DPoP 和企业 JWT grant 尚无 CLI 流程;目前提供 headers 和 client_credentials。 +- 最新任务机制属于独立的 `io.modelcontextprotocol/tasks` 扩展,本 CLI 未声明或实现该扩展;不会沿用已经移出核心的旧实验任务 API。 +- roots、sampling、logging 在最新规范中已弃用;本 CLI 不声明 roots 或 sampling,不包含 LLM 调用。stdio 日志走 stderr/daemon 日志。 +- 旧协议 unsolicited elicitation 在后台 daemon 中显式取消;需要人工输入的流程应使用新版多轮交互。 +- 自动列表变更订阅已经启用;独立的长期资源内容 watch 命令仍未提供。 + +这些能力需要各自的产品流程和互操作测试,不能靠增加 capability 标志宣称支持。 + +## 验证 + +`npm run check` 执行 TypeScript 编译及全部单元/集成测试;`npm run test:coverage` 输出覆盖率。CLI 子进程使用新编译输出,独立配置目录及随机端口,并清理自己启动的进程。实际协议测试使用官方新旧 SDK,覆盖成功、失败、分页、认证、输入续接和子进程生命周期。 + +本次在 Node 20.20.2 和 24.19.0 上运行全部 149 项测试,均通过。行覆盖率从升级前的 15.13% 提升到 77.16%;配置模块为 98.68%,MCP 客户端为 93.33%。CI 增加 Node 20/22/24 矩阵及覆盖率门槛:整体行/语句 70%、分支 60%、函数 75%,配置行/分支 90%,客户端行 90% / 分支 75%。 + +覆盖率统计来自 Vitest 当前进程;独立 CLI 子进程执行的代码不会自动合并进该数字。因此同时审阅覆盖率、进程退出码和真实请求断言,不能仅凭用例数量或总百分比判断完整性。 diff --git a/examples/weather-server.mjs b/examples/weather-server.mjs new file mode 100644 index 0000000..684316c --- /dev/null +++ b/examples/weather-server.mjs @@ -0,0 +1,24 @@ +import { McpServer } from '@modelcontextprotocol/server'; +import { serveStdio } from '@modelcontextprotocol/server/stdio'; +import * as z from 'zod/v4'; + +// A local development example. It returns simulated data and needs no network or credentials. +serveStdio(() => { + const server = new McpServer({ name: 'mcps-local-weather-example', version: '1.0.0' }); + server.registerTool('get_weather', { + inputSchema: z.object({ city: z.string(), country: z.string() }), + outputSchema: z.object({ + temperature: z.object({ celsius: z.number(), fahrenheit: z.number() }), + conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), + humidity: z.number().min(0).max(100), + wind: z.object({ speed_kmh: z.number(), direction: z.string() }), + }), + }, async () => ({ + content: [], + structuredContent: { + temperature: { celsius: 24, fahrenheit: 75.2 }, + conditions: 'sunny', humidity: 50, wind: { speed_kmh: 10, direction: 'N' }, + }, + })); + return server; +}); diff --git a/package-lock.json b/package-lock.json index 870d424..0c8443a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,26 +1,27 @@ { "name": "@maplezzk/mcps", - "version": "1.7.0", + "version": "1.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@maplezzk/mcps", - "version": "1.7.0", + "version": "1.8.0", "license": "ISC", "dependencies": { - "@modelcontextprotocol/sdk": "^1.25.3", + "@modelcontextprotocol/client": "2.3.1", "chalk": "^5.6.2", "commander": "^14.0.2", "conf": "^15.0.2", - "eventsource": "^4.1.0", "zod": "^3.24.1" }, "bin": { "mcps": "dist/index.js" }, "devDependencies": { - "@types/eventsource": "^1.1.15", + "@modelcontextprotocol/node": "2.1.1", + "@modelcontextprotocol/sdk": "1.25.3", + "@modelcontextprotocol/server": "2.3.1", "@types/node": "^22.10.7", "@vitest/coverage-v8": "^4.0.18", "@vitest/ui": "^4.0.18", @@ -548,6 +549,7 @@ "version": "1.19.9", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.9.tgz", "integrity": "sha512-vHL6w3ecZsky+8P5MD+eFfaGTyCeOHUIFYMGpQGbrBTSmNNoxv0if69rEZ5giu36weC5saFuznL411gRX7bJDw==", + "dev": true, "license": "MIT", "engines": { "node": ">=18.14.1" @@ -584,10 +586,88 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz", + "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.3.1", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.8", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/client/node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@modelcontextprotocol/client/node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz", + "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==", + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core/node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/@modelcontextprotocol/node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.1.tgz", + "integrity": "sha512-EY92OAXN2xYL7tNS/MVsWJW1v8VHAPwl9B4Ca3pCrjmvqyC+S1C/6UHsMxF2GoFPraS5Yyg56vFz9brVpFojMA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@hono/node-server": "^1.19.9", + "hono": "^4.11.4" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/server": "^2.3.0" + } + }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.25.3", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.25.3.tgz", "integrity": "sha512-vsAMBMERybvYgKbg/l4L1rhS7VXV1c0CtyJg72vwxONVX0l4ZfKVAnZEWTQixJGTzKnELjQ59e4NbdFDALRiAQ==", + "dev": true, "license": "MIT", "dependencies": { "@hono/node-server": "^1.19.9", @@ -627,6 +707,7 @@ "version": "3.0.7", "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "dev": true, "license": "MIT", "dependencies": { "eventsource-parser": "^3.0.1" @@ -635,6 +716,30 @@ "node": ">=18.0.0" } }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.3.1.tgz", + "integrity": "sha512-e59MfWuSssj6DoQ96JCTqdW1AXT5/XtnTl0WWd6MU1Ka434fFUGGosCLJbGNySDhHGvxQWoRWK137FXYFkYNWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.3.1", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/server/node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/@polka/url": { "version": "1.0.0-next.29", "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz", @@ -1052,13 +1157,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/eventsource": { - "version": "1.1.15", - "resolved": "https://registry.npmjs.org/@types/eventsource/-/eventsource-1.1.15.tgz", - "integrity": "sha512-XQmGcbnxUNa06HR3VBVkc9+A2Vpi9ZyLJcdS5dwaQQ/4ZMWFO+5c90FnMUpbtMZwB/FChoYHwuVg8TvkECacTA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/node": { "version": "22.19.7", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.7.tgz", @@ -1237,6 +1335,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "dev": true, "license": "MIT", "dependencies": { "mime-types": "^3.0.0", @@ -1359,6 +1458,7 @@ "version": "2.2.2", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", + "dev": true, "license": "MIT", "dependencies": { "bytes": "^3.1.2", @@ -1383,6 +1483,7 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -1392,6 +1493,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -1405,6 +1507,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -1475,6 +1578,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -1488,6 +1592,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -1497,6 +1602,7 @@ "version": "0.7.2", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -1506,6 +1612,7 @@ "version": "1.2.2", "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "dev": true, "license": "MIT", "engines": { "node": ">=6.6.0" @@ -1515,6 +1622,7 @@ "version": "2.8.6", "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "dev": true, "license": "MIT", "dependencies": { "object-assign": "^4", @@ -1568,6 +1676,7 @@ "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, "license": "MIT", "dependencies": { "ms": "^2.1.3" @@ -1585,6 +1694,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -1619,6 +1729,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.1", @@ -1633,12 +1744,14 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "dev": true, "license": "MIT" }, "node_modules/encodeurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -1660,6 +1773,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -1669,6 +1783,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -1685,6 +1800,7 @@ "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0" @@ -1739,6 +1855,7 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "dev": true, "license": "MIT" }, "node_modules/estree-walker": { @@ -1755,27 +1872,16 @@ "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" } }, - "node_modules/eventsource": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-4.1.0.tgz", - "integrity": "sha512-2GuF51iuHX6A9xdTccMTsNb7VO0lHZihApxhvQzJB5A03DvHDd2FQepodbMaztPBmBcE/ox7o2gqaxGhYB9LhQ==", - "license": "MIT", - "dependencies": { - "eventsource-parser": "^3.0.1" - }, - "engines": { - "node": ">=20.0.0" - } - }, "node_modules/eventsource-parser": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", - "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", "license": "MIT", "engines": { "node": ">=18.0.0" @@ -1795,6 +1901,7 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "dev": true, "license": "MIT", "dependencies": { "accepts": "^2.0.0", @@ -1838,6 +1945,7 @@ "version": "7.5.1", "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz", "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 16" @@ -1900,6 +2008,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "dev": true, "license": "MIT", "dependencies": { "debug": "^4.4.0", @@ -1928,6 +2037,7 @@ "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -1937,6 +2047,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -1961,6 +2072,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -1970,6 +2082,7 @@ "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", @@ -1994,6 +2107,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, "license": "MIT", "dependencies": { "dunder-proto": "^1.0.1", @@ -2007,6 +2121,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2029,6 +2144,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2041,6 +2157,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -2053,8 +2170,8 @@ "version": "4.11.7", "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.7.tgz", "integrity": "sha512-l7qMiNee7t82bH3SeyUCt9UF15EVmaBvsppY2zQtrbIhl/yzBTny+YUxsVjSjQ6gaqaeVtZmGocom8TzBlA4Yw==", + "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=16.9.0" } @@ -2070,6 +2187,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dev": true, "license": "MIT", "dependencies": { "depd": "~2.0.0", @@ -2090,6 +2208,7 @@ "version": "0.7.2", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "dev": true, "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -2106,12 +2225,14 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true, "license": "ISC" }, "node_modules/ipaddr.js": { "version": "1.9.1", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.10" @@ -2121,6 +2242,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "dev": true, "license": "MIT" }, "node_modules/isexe": { @@ -2245,6 +2367,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2254,6 +2377,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -2263,6 +2387,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -2275,6 +2400,7 @@ "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -2284,6 +2410,7 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "dev": true, "license": "MIT", "dependencies": { "mime-db": "^1.54.0" @@ -2322,6 +2449,7 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, "license": "MIT" }, "node_modules/nanoid": { @@ -2347,6 +2475,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -2356,6 +2485,7 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -2365,6 +2495,7 @@ "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2388,6 +2519,7 @@ "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dev": true, "license": "MIT", "dependencies": { "ee-first": "1.1.1" @@ -2400,6 +2532,7 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, "license": "ISC", "dependencies": { "wrappy": "1" @@ -2409,6 +2542,7 @@ "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -2427,6 +2561,7 @@ "version": "8.3.0", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "dev": true, "license": "MIT", "funding": { "type": "opencollective", @@ -2502,6 +2637,7 @@ "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dev": true, "license": "MIT", "dependencies": { "forwarded": "0.2.0", @@ -2515,6 +2651,7 @@ "version": "6.14.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "dev": true, "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" @@ -2530,6 +2667,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" @@ -2539,6 +2677,7 @@ "version": "3.0.2", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "dev": true, "license": "MIT", "dependencies": { "bytes": "~3.1.2", @@ -2608,6 +2747,7 @@ "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "dev": true, "license": "MIT", "dependencies": { "debug": "^4.4.0", @@ -2624,6 +2764,7 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, "license": "MIT" }, "node_modules/semver": { @@ -2642,6 +2783,7 @@ "version": "1.2.1", "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "dev": true, "license": "MIT", "dependencies": { "debug": "^4.4.3", @@ -2668,6 +2810,7 @@ "version": "2.2.1", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "dev": true, "license": "MIT", "dependencies": { "encodeurl": "^2.0.0", @@ -2687,6 +2830,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true, "license": "ISC" }, "node_modules/shebang-command": { @@ -2714,6 +2858,7 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -2733,6 +2878,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -2749,6 +2895,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -2767,6 +2914,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -2825,6 +2973,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -2925,6 +3074,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, "license": "MIT", "engines": { "node": ">=0.6" @@ -3003,6 +3153,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "dev": true, "license": "MIT", "dependencies": { "content-type": "^1.0.5", @@ -3050,6 +3201,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -3066,6 +3218,7 @@ "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" @@ -3266,6 +3419,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, "license": "ISC" }, "node_modules/yn": { @@ -3291,6 +3445,7 @@ "version": "3.25.1", "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", + "dev": true, "license": "ISC", "peerDependencies": { "zod": "^3.25 || ^4" diff --git a/package.json b/package.json index 511e20f..a261485 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@maplezzk/mcps", - "version": "1.7.0", + "version": "1.8.0", "description": "A CLI to manage and use MCP servers", "publishConfig": { "access": "public" @@ -23,13 +23,15 @@ "mcps": "./dist/index.js" }, "files": [ - "dist" + "dist", + "!dist/tests", + "docs/MCP_SUPPORT.md" ], "scripts": { "build": "tsc", "prepublishOnly": "npm run build && npm run test", "start": "node dist/index.js", - "dev": "ts-node src/index.ts", + "dev": "node --loader ts-node/esm src/index.ts", "check": "npm run build && npm test", "test": "vitest run", "test:watch": "vitest", @@ -37,15 +39,16 @@ "test:coverage": "vitest --coverage" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.25.3", + "@modelcontextprotocol/client": "2.3.1", "chalk": "^5.6.2", "commander": "^14.0.2", "conf": "^15.0.2", - "eventsource": "^4.1.0", "zod": "^3.24.1" }, "devDependencies": { - "@types/eventsource": "^1.1.15", + "@modelcontextprotocol/node": "2.1.1", + "@modelcontextprotocol/sdk": "1.25.3", + "@modelcontextprotocol/server": "2.3.1", "@types/node": "^22.10.7", "@vitest/coverage-v8": "^4.0.18", "@vitest/ui": "^4.0.18", diff --git a/src/commands/call.ts b/src/commands/call.ts index 11e73ce..3a7b921 100644 --- a/src/commands/call.ts +++ b/src/commands/call.ts @@ -55,18 +55,34 @@ export function loadJsonParams(jsonValue: string): Record { } } -function printResult(result: any) { +export function printResult(result: any) { + if (result.resultType === 'input_required') { + console.log(JSON.stringify(result, null, 2)); + return; + } if (result.content) { (result.content as any[]).forEach((item: any) => { if (item.type === 'text') { console.log(item.text); } else if (item.type === 'image') { console.log(`[Image: ${item.mimeType}]`); + } else if (item.type === 'audio') { + console.log(`[Audio: ${item.mimeType}]`); + } else if (item.type === 'resource_link') { + console.log(`[Resource: ${item.uri}]`); } else if (item.type === 'resource') { - console.log(`[Resource: ${item.resource.uri}]`); + console.log(item.resource.text ?? `[Resource: ${item.resource.uri}]`); } }); - } else { + } + if (result.structuredContent !== undefined) { + const alreadyPrinted = result.content?.some((item: any) => { + if (item.type !== 'text') return false; + try { return JSON.stringify(JSON.parse(item.text)) === JSON.stringify(result.structuredContent); } + catch { return false; } + }); + if (!alreadyPrinted) console.log(JSON.stringify(result.structuredContent, null, 2)); + } else if (!result.content) { console.log(JSON.stringify(result, null, 2)); } } @@ -76,7 +92,10 @@ export const registerCallCommand = (program: Command) => { .description('Call a tool on a server. Arguments format: key=value') .option('-r, --raw', 'Treat all values as raw strings (no JSON parsing)') .option('-j, --json ', 'Load parameters from a JSON file') - .option('-t, --timeout ', 'Request timeout in seconds (default: 60)') + .option('--output-json', 'Output the complete MCP result without losing content or metadata') + .option('--input-responses ', 'MCP input responses as a JSON object or file') + .option('--request-state ', 'Opaque MCP request state returned by the server') + .option('-t, --timeout ', 'Request timeout in seconds (default: 300)') .addHelpText('after', ` Examples: $ mcps call my-server echo message="Hello World" @@ -98,7 +117,7 @@ Notes: - By default, values are automatically parsed as JSON if possible (numbers, booleans, objects). - Use --raw to disable JSON parsing and treat all values as strings. - Use --json to load parameters from a JSON file or JSON string. - - Use --timeout to override the default 60s request timeout. + - Use --timeout to override the default 300s request timeout. - For strings with spaces, wrap the value in quotes (e.g., msg="hello world"). `) .action(async (serverName, toolName, args, options) => { @@ -110,35 +129,41 @@ Notes: params = loadJsonParams(options.json as string); } catch (error: any) { console.error(chalk.red(`Failed to parse JSON: ${error.message}`)); - process.exit(1); + process.exitCode = 1; + return; } } else { params = parseCallArgs(args, options.raw); } - // Check if server exists in config first - const serverConfig = configManager.getServer(serverName); - if (!serverConfig) { - console.error(chalk.red(`Server "${serverName}" not found in config.`)); - process.exit(1); - } - try { + if (!params || typeof params !== 'object' || Array.isArray(params)) throw new Error('Tool arguments must be a JSON object'); + const serverConfig = configManager.getServer(serverName); + if (!serverConfig) throw new Error(`Server "${serverName}" not found in config.`); + if (serverConfig.disabled) throw new Error(`Server "${serverName}" is disabled.`); + const seconds = Number(options.timeout ?? 300); + if (!Number.isFinite(seconds) || seconds <= 0) throw new Error('Request timeout must be positive'); + const continuation = options.inputResponses ? loadJsonParams(options.inputResponses) : undefined; + if (continuation && (typeof continuation !== 'object' || Array.isArray(continuation))) throw new Error('Input responses must be a JSON object'); // Auto-start daemon if needed await DaemonClient.ensureDaemon(); // Parse timeout option (convert seconds to ms for SDK, default 5min = 300s) - const timeout = (options.timeout ? parseInt(options.timeout as string, 10) : 300) * 1000; + const timeout = seconds * 1000; // Execute via daemon - const result = await DaemonClient.executeTool(serverName, toolName, params, timeout); - console.log(chalk.green('Tool execution successful:')); - printResult(result); + const result = await DaemonClient.executeTool(serverName, toolName, params, timeout, { inputResponses: continuation, requestState: options.requestState }); + if (options.outputJson) console.log(JSON.stringify(result, null, 2)); + else { + if (result.resultType !== 'input_required') console.log(result.isError ? chalk.red('Tool execution failed:') : chalk.green('Tool execution successful:')); + printResult(result); + } + if (result.isError) process.exitCode = 1; + if (result.resultType === 'input_required') process.exitCode = 2; } catch (error: any) { console.error(chalk.red(`Execution failed: ${error.message}`)); - process.exit(1); + process.exitCode = 1; } }); }; - diff --git a/src/commands/daemon.ts b/src/commands/daemon.ts index f594816..7a34a27 100644 --- a/src/commands/daemon.ts +++ b/src/commands/daemon.ts @@ -1,699 +1,201 @@ -import { spawn } from 'child_process'; -import http from 'http'; -import net from 'net'; -import chalk from 'chalk'; +import { spawn } from 'node:child_process'; +import http from 'node:http'; +import net from 'node:net'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { createRequire } from 'node:module'; import { Command } from 'commander'; import { connectionPool } from '../core/pool.js'; -import { createRequire } from 'module'; +import { configManager } from '../core/config.js'; +import { daemonRequest } from '../core/daemon-client.js'; import { DAEMON_PORT } from '../core/constants.js'; -const require = createRequire(import.meta.url); -const pkg = require('../../package.json'); - -// Helper function to make HTTP requests to daemon (bypassing proxy) -function daemonRequest(method: string, path: string, body?: string): Promise<{ status: number; ok: boolean; data: any }> { - return new Promise((resolve, reject) => { - const port = parseInt(process.env.MCPS_PORT || String(DAEMON_PORT)); - const options = { - method, - hostname: '127.0.0.1', - port, - path, - headers: { - 'Content-Type': 'application/json', - }, - }; - - const req = http.request(options, (res) => { - let data = ''; - res.on('data', chunk => { data += chunk; }); - res.on('end', () => { - try { - resolve({ - status: res.statusCode || 500, - ok: (res.statusCode || 500) >= 200 && (res.statusCode || 500) < 300, - data: data ? JSON.parse(data) : {}, - }); - } catch (e) { - reject(e); - } - }); - }); - - req.on('error', reject); - if (body) { - req.write(body); - } - req.end(); - }); -} - -// Check if a port is in use -function isPortInUse(port: number): Promise { - return new Promise((resolve) => { - const server = net.createServer(); - - server.once('error', () => { - resolve(true); // Port is in use - }); - - server.once('listening', () => { - server.once('close', () => { - resolve(false); // Port is available - }); - server.close(); - }); +const pkg = createRequire(import.meta.url)('../../package.json'); +const fail = (error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; +}; +const portNumber = (value: string | number) => { + const port = Number(value); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Port must be an integer between 1 and 65535'); + return port; +}; +const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); - server.listen(port, '127.0.0.1'); +function portAvailable(port: number): Promise { + return new Promise(resolve => { + const probe = net.createServer(); + probe.once('error', () => resolve(false)); + probe.listen(port, '127.0.0.1', () => probe.close(() => resolve(true))); }); } -// Action functions for daemon commands -const startAction = async (options: any) => { - const port = parseInt(options.port || process.env.MCPS_PORT || DAEMON_PORT); - - // Get timeout from option, env, or config (in seconds) - let timeout = 30; // Default 30 seconds for daemon start - if (options.timeout) { - timeout = parseInt(options.timeout, 10); - } else if (process.env.MCPS_DAEMON_TIMEOUT) { - timeout = parseInt(process.env.MCPS_DAEMON_TIMEOUT, 10); - } - - // Check if port is in use (more reliable than HTTP check) - const portInUse = await isPortInUse(port); - if (portInUse) { - // Try to check if it's our daemon via HTTP - try { - const { ok } = await daemonRequest('GET', '/status'); - if (ok) { - console.log(chalk.yellow(`Daemon is already running on port ${port}.`)); - process.exit(0); - return; - } - } catch { - // Port is in use but not our daemon - console.error(chalk.red(`Port ${port} is already in use by another process.`)); - process.exit(1); +async function startAction(options: any) { + try { + const port = portNumber(options.port); + configManager.validateConfig(); + const timeout = options.timeout === undefined ? configManager.getDaemonTimeout() : Number(options.timeout) * 1000; + if (!Number.isFinite(timeout) || timeout <= 0) throw new Error('Startup timeout must be positive'); + if (!await portAvailable(port)) { + const status = await daemonRequest('GET', '/status', undefined, port, 2000); + if (status.status !== 'running' || status.configPath !== configManager.getConfigPath()) throw new Error(`Port ${port} belongs to another service or configuration`); + console.log(`Daemon is already running on port ${port}.`); return; } - } - - // If we are already detached (indicated by env var), run the server - if (process.env.MCPS_DAEMON_DETACHED === 'true') { - startDaemon(port); - return; - } - - // Otherwise, spawn a detached process - console.log(chalk.cyan('Starting daemon in background...')); - let childFailed = false; - - // Create log file paths - const logDir = '/tmp/mcps-daemon'; - const stdoutLog = `${logDir}/stdout.log`; - const stderrLog = `${logDir}/stderr.log`; - - // Ensure log directory exists - const fs = await import('fs'); - if (!fs.existsSync(logDir)) { + if (process.env.MCPS_DAEMON_DETACHED === 'true') { + startDaemon(port); + return; + } + const logDir = path.join(os.tmpdir(), 'mcps-daemon', String(port)); fs.mkdirSync(logDir, { recursive: true }); - } - - // Clear old log files for fresh start - if (fs.existsSync(stdoutLog)) { - fs.truncateSync(stdoutLog, 0); - } - if (fs.existsSync(stderrLog)) { - fs.truncateSync(stderrLog, 0); - } - - // Open file descriptors for stdout and stderr - const stdoutFd = fs.openSync(stdoutLog, 'a'); - const stderrFd = fs.openSync(stderrLog, 'a'); - - const subprocess = spawn(process.execPath, [process.argv[1], 'daemon', 'start'], { - detached: true, - // Pipe stdout/stderr to log files - stdio: ['ignore', stdoutFd, stderrFd], - env: { - ...process.env, - MCPS_DAEMON_DETACHED: 'true', - MCPS_VERBOSE: options.verbose ? 'true' : 'false', - MCPS_CONNECTION_TIMEOUT: String((parseInt(options.connectionTimeout || process.env.MCPS_CONNECTION_TIMEOUT || '20', 10)) * 1000) - } - }); - - subprocess.unref(); - - // Wait briefly to ensure it started (optional but good UX) - // We can poll status for a second - const start = Date.now(); - // Use timeout from option/env (convert to ms) - let lastLogSize = 0; // Track last read position to avoid duplicate logs - - while (Date.now() - start < timeout * 1000) { - // If child reported port conflict, check if daemon is actually running - if (childFailed) { - const stillRunning = await isPortInUse(port); - if (stillRunning) { - // Another daemon is running - console.log(chalk.yellow(`\nDaemon is already running on port ${port}.`)); - process.exit(0); - return; - } - } - - // Show only new logs (avoid duplicates) - try { - if (fs.existsSync(stdoutLog)) { - const { size } = fs.statSync(stdoutLog); - if (size > lastLogSize) { - // Read new logs only - const buffer = Buffer.alloc(size - lastLogSize); - const fd = fs.openSync(stdoutLog, 'r'); - fs.readSync(fd, buffer, 0, size - lastLogSize, lastLogSize); - fs.closeSync(fd); - - const newLogs = buffer.toString('utf-8'); - newLogs.split('\n').forEach(line => { - if (line.trim()) process.stdout.write(line + '\n'); - }); - - lastLogSize = size; - } - } - } catch (e) { - // Ignore log read errors - } - - try { - const { ok, data } = await daemonRequest('GET', '/status'); - if (ok && data.initialized) { - console.log(chalk.green(`Daemon started successfully on port ${port}.`)); - console.log(chalk.gray(`Logs: ${stdoutLog}`)); - process.exit(0); - } - } catch {} - await new Promise(r => setTimeout(r, 200)); - } - console.log(chalk.yellow('Daemon started (async check timeout, but likely running).')); - console.log(chalk.gray(`Logs: ${stdoutLog}`)); - process.exit(0); -}; - -const stopAction = async (options?: any) => { - try { - const logPath = '/tmp/mcps-daemon/stdout.log'; - const fs = await import('fs'); - - // 发送 stop 请求并显示日志 - const requestPromise = daemonRequest('POST', '/stop'); - - // 显示关闭日志 - const showLogs = async () => { - try { - if (!fs.existsSync(logPath)) { - return; - } - - let lastSize = fs.statSync(logPath).size; - const startTime = Date.now(); - const timeout = 5000; // 5秒超时 - - while (Date.now() - startTime < timeout) { - await new Promise(r => setTimeout(r, 200)); - - try { - const { size: currentSize } = fs.statSync(logPath); - if (currentSize > lastSize) { - const buffer = Buffer.alloc(currentSize - lastSize); - const fd = fs.openSync(logPath, 'r'); - fs.readSync(fd, buffer, 0, currentSize - lastSize, lastSize); - fs.closeSync(fd); - - const newLogs = buffer.toString('utf-8'); - const relevantLogs = newLogs.split('\n').filter(line => { - return line.includes('Closing connection to') || - line.includes('Shutting down'); - }); - - if (relevantLogs.length > 0) { - relevantLogs.forEach(log => { - if (log.trim()) { - console.log(chalk.yellow(log)); - } - }); - lastSize = currentSize; - } - } - } catch (e) { - // 忽略读取错误 - } - } - } catch (e) { - // 忽略日志显示错误 - } - }; - - const [{ ok }] = await Promise.all([ - requestPromise, - showLogs() - ]); - - if (ok) { - console.log(chalk.green('Daemon stopped successfully.')); - } - } catch (e) { - console.error(chalk.red('Failed to stop daemon. Is it running?')); - } -}; - -const statusAction = async (options?: any) => { - try { - const { data } = await daemonRequest('GET', '/status'); - - console.log(''); - console.log(chalk.green(`Daemon is running (v${data.version})`)); - - if (data.connections && data.connections.length > 0) { - // Helper function to calculate display width (Chinese chars count as 2) - const getDisplayWidth = (str: string): number => { - let width = 0; - for (const char of str) { - if (char.charCodeAt(0) > 127) { - width += 2; - } else { - width += 1; - } - } - return width; - }; - - // Helper function to pad string considering Chinese characters - const padEndWidth = (str: string, targetWidth: number): string => { - const displayWidth = getDisplayWidth(str); - const padding = Math.max(0, targetWidth - displayWidth); - return str + ' '.repeat(padding); - }; - - // Build table rows - const rows = data.connections.map((conn: any) => { - const statusText = conn.status === 'error' ? 'Error' : 'Connected'; - const statusColor = conn.status === 'error' ? chalk.red : chalk.green; - const toolsCount = conn.toolsCount !== null ? conn.toolsCount : '-'; - - return { - name: conn.name, - status: statusColor(statusText), - tools: toolsCount - }; - }); - - // Calculate column widths - const nameWidth = Math.max(4, ...rows.map((r: any) => getDisplayWidth(r.name))); - const statusWidth = 10; - const toolsWidth = 6; - - // Print table header - console.log(chalk.bold('\nActive Connections:')); - console.log(chalk.bold(`${'NAME'.padEnd(nameWidth)} ${'STATUS'.padEnd(statusWidth)} ${'TOOLS'}`)); - console.log(chalk.cyan('─'.repeat(nameWidth) + ' ' + '─'.repeat(statusWidth) + ' ' + '─'.repeat(toolsWidth))); - - // Print table rows - rows.forEach((row: any) => { - console.log(`${padEndWidth(row.name, nameWidth)} ${String(row.status).padEnd(statusWidth)} ${String(row.tools)}`); - }); - - console.log(chalk.cyan(`Total: ${data.connections.length} connection(s)`)); - } else { - console.log(chalk.yellow('\nNo active connections.')); - } - - console.log(''); - } catch (e) { - console.error(chalk.red('Daemon is not running.')); - } -}; - -const restartAction = async (serverName: string | undefined, options?: any) => { - try { - const body = serverName ? JSON.stringify({ server: serverName }) : JSON.stringify({}); - - // 启动日志显示(在后台读取守护进程日志) - const logPath = '/tmp/mcps-daemon/stdout.log'; - const fs = await import('fs'); - - // 发送 restart 请求 - const requestPromise = daemonRequest('POST', '/restart', body); - - // 在后台显示日志 - const showLogs = async () => { - try { - if (!fs.existsSync(logPath)) { - return; - } - - // 获取当前日志文件大小 - let lastSize = fs.statSync(logPath).size; - - // 等待请求完成,同时显示新日志 - const startTime = Date.now(); - const timeout = 30000; // 30秒超时 - - while (Date.now() - startTime < timeout) { - await new Promise(r => setTimeout(r, 200)); // 每200ms检查一次 - - try { - const { size: currentSize } = fs.statSync(logPath); - if (currentSize > lastSize) { - // 读取新增的日志内容 - const buffer = Buffer.alloc(currentSize - lastSize); - const fd = fs.openSync(logPath, 'r'); - fs.readSync(fd, buffer, 0, currentSize - lastSize, lastSize); - fs.closeSync(fd); - - const newLogs = buffer.toString('utf-8'); - // 只显示关闭和重启相关的日志 - const relevantLogs = newLogs.split('\n').filter(line => { - return line.includes('Closing connection to') || - line.includes('Connected ✓') || - line.includes('Connecting to') || - line.includes('Connected: ') || - line.trim().startsWith('- '); // 包含服务名行 - }); - - if (relevantLogs.length > 0) { - // 检查是否已经完成 - const hasCompletion = newLogs.includes('All servers reinitialized successfully'); - - relevantLogs.forEach(log => { - if (log.trim()) { - if (log.includes('Closing')) { - console.log(chalk.yellow(log)); - } else if (log.includes('Connected ✓')) { - console.log(chalk.green(log)); - } else if (log.includes('Connected:')) { - // 最终连接统计 - console.log(chalk.green(log)); - } else { - console.log(log); - } - } - }); - - if (hasCompletion) { - break; // 完成后退出 - } - - // 更新起始位置 - lastSize = currentSize; - } - } - } catch (e) { - // 忽略读取错误 - } - } - } catch (e) { - // 忽略日志显示错误 - } - }; - - // 同时执行请求和日志显示 - const [{ status, ok, data }] = await Promise.all([ - requestPromise, - showLogs() - ]); - - if (ok) { - console.log(chalk.green(data.message)); - } else if (status === 404) { - console.error(chalk.yellow(data.error || 'Server not found')); - } else { - console.error(chalk.red(data.error || 'Failed to restart')); - } - } catch (e: any) { - console.error(chalk.red('Failed to restart.')); - console.error(chalk.red(`Error: ${e.message}`)); - console.error(chalk.gray(`Stack: ${e.stack}`)); - } -}; - -export const registerDaemonCommand = (program: Command) => { - // ===== Top-level commands (new, simplified) ===== - - program.command('start') - .description('Start the daemon') - .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)) - .option('-t, --timeout ', 'Startup timeout in seconds (default: 30)') - .option('-c, --connection-timeout ', 'Server connection timeout in seconds (default: 20)') - .option('-v, --verbose', 'Show detailed logs') - .action((options) => startAction(options)); - - program.command('stop') - .description('Stop the daemon') - .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)) - .action((options) => stopAction(options)); - - program.command('status') - .description('Check daemon status') - .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)) - .action((options) => statusAction(options)); - - program.command('restart [server]') - .description('Restart the daemon or a specific server connection') - .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)) - .action((serverName, options) => restartAction(serverName, options)); - - // ===== Legacy daemon subcommands (for backward compatibility) ===== - - const daemonCmd = program.command('daemon') - .description('Manage the mcps daemon (legacy, use top-level commands)') - .usage('start|stop|restart|status') - .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)); - - daemonCmd.command('start', { isDefault: true, hidden: true }) - .description('Start the daemon (default)') - .option('-t, --timeout ', 'Startup timeout in seconds (default: 30)') - .option('-c, --connection-timeout ', 'Server connection timeout in seconds (default: 20)') - .action((options) => startAction(options)); - - daemonCmd.command('stop') - .description('Stop the running daemon') - .action((options) => stopAction(options)); - - daemonCmd.command('status') - .description('Check daemon status') - .action((options) => statusAction(options)); - - daemonCmd.command('restart [server]') - .description('Restart the daemon or a specific server connection') - .action((serverName, options) => restartAction(serverName, options)); -}; - -const startDaemon = (port: number) => { - const server = http.createServer(async (req, res) => { - // Basic Error Handling - req.on('error', (err) => { - console.error('[Daemon] Request error:', err); + const stdoutLog = path.join(logDir, 'stdout.log'); + const stderrLog = path.join(logDir, 'stderr.log'); + const stdout = fs.openSync(stdoutLog, 'a'); + const stderr = fs.openSync(stderrLog, 'a'); + const connectionTimeout = Number(options.connectionTimeout ?? '20'); + if (!Number.isFinite(connectionTimeout) || connectionTimeout <= 0) throw new Error('Connection timeout must be positive'); + console.log('Starting daemon in background...'); + const child = spawn(process.execPath, [...process.execArgv, process.argv[1], 'start', '--port', String(port)], { + detached: true, stdio: ['ignore', stdout, stderr], + env: { ...process.env, MCPS_PORT: String(port), MCPS_DAEMON_DETACHED: 'true', MCPS_VERBOSE: String(Boolean(options.verbose)), MCPS_CONNECTION_TIMEOUT: String(connectionTimeout * 1000) }, }); - - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS'); - res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); - - if (req.method === 'OPTIONS') { - res.writeHead(204); - res.end(); - return; - } - - if (req.method === 'GET' && req.url === '/status') { - const initStatus = connectionPool.getInitStatus(); - const connections = await connectionPool.getActiveConnectionDetails(!initStatus.initializing); - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - status: 'running', - version: pkg.version, - connections, - ...initStatus - })); - return; - } - - // ... (restart/stop/call handlers) ... - if (req.method === 'POST' && req.url === '/restart') { - let body = ''; - req.on('data', chunk => { body += chunk.toString(); }); - req.on('end', async () => { - try { - const { server: serverName } = JSON.parse(body || '{}'); - const verbose = process.env.MCPS_VERBOSE === 'true'; - - if (verbose) { - console.log(`[Daemon] Received restart request for: ${serverName || 'all servers'}`); - } - - if (serverName) { - // Restart specific server connection - if (verbose) { - console.log(`[Daemon] Closing server: ${serverName}`); - } - const closed = await connectionPool.closeClient(serverName); - if (closed) { - // Reconnect to the specific server - try { - if (verbose) { - console.log(`[Daemon] Reconnecting to: ${serverName}`); - } - await connectionPool.getClient(serverName); - if (verbose) { - console.log(`[Daemon] Successfully restarted: ${serverName}`); - } - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ message: `Server "${serverName}" restarted successfully.` })); - } catch (error: any) { - console.error(`[Daemon] Failed to reconnect to ${serverName}:`, error); - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: `Failed to reconnect to "${serverName}": ${error.message}` })); - } - } else { - if (verbose) { - console.log(`[Daemon] Server not found: ${serverName}`); - } - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: `Server "${serverName}" not found or not connected.` })); - } - } else { - // Restart all connections - console.log('Closing all connections...'); - await connectionPool.closeAll(); - console.log('All connections closed. Reinitializing...'); - // Reinitialize all servers - await connectionPool.initializeAll(); - console.log('All servers reinitialized successfully'); - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ message: 'All servers restarted successfully.' })); - } - } catch (error: any) { - console.error('[Daemon] Error during restart:', error); - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: error.message })); - } - }); - return; - } - - if (req.method === 'POST' && req.url === '/stop') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ message: 'Daemon shutting down...' })); - setTimeout(() => { - server.close(); - connectionPool.closeAll(); - process.exit(0); - }, 100); - return; - } - - if (req.method === 'POST' && req.url === '/call') { - let body = ''; - req.on('data', chunk => { body += chunk.toString(); }); - req.on('end', async () => { - try { - const { server: serverName, tool, args, timeout } = JSON.parse(body); - - if (!serverName || !tool) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Missing server or tool' })); - return; - } - - const client = await connectionPool.getClient(serverName); - const result = await client.callTool(tool, args || {}, timeout); - - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ result })); - } catch (error: any) { - console.error(`[Daemon] Error executing tool:`, error); - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: error.message })); - } - }); + fs.closeSync(stdout); + fs.closeSync(stderr); + child.unref(); + let childError: Error | undefined; + child.on('error', error => { childError = error; }); + const started = Date.now(); + while (Date.now() - started < timeout) { + if (childError) throw childError; + try { + const status = await daemonRequest('GET', '/status', undefined, port, 1000); + if (status.initialized && status.configPath === configManager.getConfigPath()) { + console.log(`Daemon started successfully on port ${port}.`); + console.log(`Logs: ${stdoutLog}, ${stderrLog}`); return; } + } catch {} + await delay(100); + } + throw new Error(`Daemon did not initialize within ${timeout / 1000}s. Inspect ${stderrLog}`); + } catch (error) { fail(error); } +} - if (req.method === 'POST' && req.url === '/list') { - let body = ''; - req.on('data', chunk => { body += chunk.toString(); }); - req.on('end', async () => { - try { - const { server: serverName } = JSON.parse(body); - - if (!serverName) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'Missing server name' })); - return; - } - - // Try to use cached tools first - const cachedTools = connectionPool.getCachedTools(serverName); - if (cachedTools !== null) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ tools: cachedTools })); - return; - } +async function statusAction(options: any) { + try { + const status = await daemonRequest('GET', '/status', undefined, portNumber(options.port), 5000); + if (options.json) { + console.log(JSON.stringify(status, null, 2)); + return; + } + console.log(`Daemon is running (v${status.version})`); + console.table(status.connections.map((connection: any) => ({ + NAME: connection.name, STATUS: connection.status, TOOLS: connection.toolsCount, + PROTOCOL: connection.protocolVersion, ERA: connection.protocolEra, + }))); + } catch (error) { fail(error); } +} - // Fallback: fetch from client if not cached - const client = await connectionPool.getClient(serverName); - const toolsResult = await client.listTools(); +async function stopAction(options: any) { + try { + const result = await daemonRequest('POST', '/stop', undefined, portNumber(options.port), 10000); + console.log(result.message); + } catch (error) { fail(error); } +} - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify(toolsResult)); - } catch (error: any) { - console.error(`[Daemon] Error listing tools:`, error); - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: error.message })); - } - }); - return; - } +async function restartAction(server: string | undefined, options: any) { + try { + const result = await daemonRequest('POST', '/restart', { server }, portNumber(options.port)); + console.log(result.message); + } catch (error) { fail(error); } +} - res.writeHead(404); - res.end(); - }); +export function registerDaemonCommand(program: Command) { + const register = (target: Command) => { + target.command('start').description('Start the daemon') + .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)) + .option('-t, --timeout ', 'Startup timeout') + .option('-c, --connection-timeout ', 'Server connection timeout', '20') + .option('-v, --verbose', 'Show detailed logs').action(startAction); + target.command('status').description('Inspect daemon connections and negotiated protocols') + .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)) + .option('-j, --json', 'Output complete status JSON').action(statusAction); + target.command('stop').description('Stop the daemon') + .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)).action(stopAction); + target.command('restart [server]').description('Restart server connections') + .option('-p, --port ', 'Daemon port', String(DAEMON_PORT)).action(restartAction); + }; + register(program); + register(program.command('daemon').description('Legacy daemon subcommands')); +} - server.listen(port, async () => { - // Initialize all connections eagerly - try { - await connectionPool.initializeAll(); - } catch (error: any) { - console.error('[Daemon] Error during initialization:', error.message); - // Don't exit, continue running with partial connections - } - }); - - server.on('error', (e: any) => { - if (e.code === 'EADDRINUSE') { - console.error(chalk.red(`Port ${port} is already in use by another daemon.`)); - process.exit(1); // Exit with error if port is in use +export function startDaemon(port: number) { + const server = http.createServer(async (request, response) => { + response.setHeader('Content-Type', 'application/json'); + const send = (status: number, body: unknown) => { + response.writeHead(status); + response.end(JSON.stringify(body)); + }; + try { + if (request.method === 'GET' && request.url === '/status') { + const initialization = connectionPool.getInitStatus(); + send(200, { status: 'running', version: pkg.version, configPath: configManager.getConfigPath(), connections: await connectionPool.getActiveConnectionDetails(!initialization.initializing), ...initialization }); + return; + } + if (request.method !== 'POST') { send(404, { error: 'Unknown daemon endpoint' }); return; } + let raw = ''; + for await (const chunk of request) raw += chunk.toString(); + let body: any; + try { body = raw ? JSON.parse(raw) : {}; } catch { send(400, { error: 'Invalid request JSON' }); return; } + if (!body || typeof body !== 'object' || Array.isArray(body)) { send(400, { error: 'Request body must be an object' }); return; } + if (request.url === '/stop') { + await connectionPool.closeAll(); + send(200, { message: 'Daemon stopped successfully.' }); + setTimeout(() => { server.close(); process.exit(0); }, 100); + return; + } + if (request.url === '/restart') { + if (body.server) { + await connectionPool.closeClient(body.server); + await connectionPool.getClient(body.server); } else { - console.error('[Daemon] Server error:', e); - process.exit(1); + await connectionPool.closeAll(); + await connectionPool.initializeAll(); } - }); - - const shutdown = async () => { - console.log('\n[Daemon] Shutting down...'); - server.close(); - await connectionPool.closeAll(); - process.exit(0); - }; - - process.on('SIGINT', shutdown); - process.on('SIGTERM', shutdown); - - // Prevent unhandled rejections from crashing the daemon - process.on('unhandledRejection', (reason, promise) => { - console.error('[Daemon] Unhandled Rejection at:', promise, 'reason:', reason); - }); -}; + send(200, { message: 'Server connections restarted.' }); + return; + } + if (!['/call', '/list', '/protocol'].includes(request.url ?? '')) { send(404, { error: 'Unknown daemon endpoint' }); return; } + if (typeof body.server !== 'string' || !body.server) { send(400, { error: 'Server name is required' }); return; } + const client = await connectionPool.getClient(body.server, { timeoutMs: 20000 }); + if (request.url === '/list') { + send(200, await client.listTools()); + } else if (request.url === '/call') { + if (typeof body.tool !== 'string' || !body.tool) { send(400, { error: 'Tool name is required' }); return; } + const result = await client.callTool(body.tool, body.args ?? {}, body.timeout, { inputResponses: body.inputResponses, requestState: body.requestState }); + send(200, { result }); + } else { + send(200, { result: await client.request(body.operation, body.params, body.timeout) }); + } + } catch (error: any) { + send(500, { error: error.message, code: error.code, data: error.data }); + } + }); + server.listen(port, '127.0.0.1', async () => { + try { await connectionPool.initializeAll(); } catch (error) { console.error(error); } + }); + server.on('error', error => { console.error(error.message); process.exit(1); }); + const shutdown = async () => { + await connectionPool.closeAll(); + server.close(); + process.exit(0); + }; + process.once('SIGINT', shutdown); + process.once('SIGTERM', shutdown); + server.once('close', () => { + process.removeListener('SIGINT', shutdown); + process.removeListener('SIGTERM', shutdown); + }); + return server; +} diff --git a/src/commands/protocol.ts b/src/commands/protocol.ts new file mode 100644 index 0000000..483c2b2 --- /dev/null +++ b/src/commands/protocol.ts @@ -0,0 +1,58 @@ +import { Command } from 'commander'; +import { DaemonClient } from '../core/daemon-client.js'; +import { configManager } from '../core/config.js'; +import { type ProtocolOperation } from '../core/client.js'; +import { loadJsonParams, parseCallArgs } from './call.js'; + +export function registerProtocolCommands(program: Command) { + const invoke = async (server: string, operation: ProtocolOperation, params: Record = {}) => { + try { + const configured = configManager.getServer(server); + if (!configured) throw new Error(`Server "${server}" not found in config.`); + if (configured.disabled) throw new Error(`Server "${server}" is disabled.`); + await DaemonClient.ensureDaemon(); + const result: any = await DaemonClient.request(server, operation, params); + console.log(JSON.stringify(result, null, 2)); + if (result.resultType === 'input_required') process.exitCode = 2; + } catch (error: any) { + console.error(error.message); + process.exitCode = 1; + } + }; + const continuation = (options: any) => ({ + ...(options.requestState !== undefined ? { requestState: options.requestState } : {}), + ...(options.inputResponses ? { inputResponses: loadJsonParams(options.inputResponses) } : {}), + }); + const continuable = (command: Command) => command + .option('--input-responses ', 'JSON input responses or file for a multi-round-trip request') + .option('--request-state ', 'Opaque request state returned by the server'); + program.command('discover ').description('Show negotiated MCP protocol, server capabilities and discovery result') + .action(server => invoke(server, 'info')); + program.command('resources ').description('List all MCP resources or resource templates') + .option('--templates', 'List resource templates') + .action((server, options) => invoke(server, options.templates ? 'resources/templates/list' : 'resources/list')); + continuable(program.command('read ').description('Read an MCP resource')) + .action(async (server, uri, options) => { + try { await invoke(server, 'resources/read', { uri, ...continuation(options) }); } + catch (error: any) { console.error(error.message); process.exitCode = 1; } + }); + program.command('prompts ').description('List all MCP prompts') + .action(server => invoke(server, 'prompts/list')); + continuable(program.command('prompt [args...]').description('Get an MCP prompt with string KEY=VALUE arguments')) + .option('-j, --json ', 'Prompt arguments as JSON or a file') + .action(async (server, name, args, options) => { + try { + const values = options.json ? loadJsonParams(options.json) : parseCallArgs(args, true); + if (!values || typeof values !== 'object' || Array.isArray(values) || Object.values(values).some(value => typeof value !== 'string')) { + throw new Error('Prompt arguments must be a JSON object with string values'); + } + await invoke(server, 'prompts/get', { name, arguments: values, ...continuation(options) }); + } catch (error: any) { console.error(error.message); process.exitCode = 1; } + }); + program.command('complete ').description('Complete a prompt or resource-template argument') + .requiredOption('-j, --json ', 'MCP completion parameters as JSON or a file') + .action(async (server, options) => { + try { await invoke(server, 'completion/complete', loadJsonParams(options.json)); } + catch (error: any) { console.error(error.message); process.exitCode = 1; } + }); +} diff --git a/src/commands/server.ts b/src/commands/server.ts index b0ca1ae..c1c2897 100644 --- a/src/commands/server.ts +++ b/src/commands/server.ts @@ -6,6 +6,23 @@ import { DaemonClient } from '../core/daemon-client.js'; import { detectServerType } from '../types/config.js'; import { DAEMON_PORT } from '../core/constants.js'; +export function parseAssignments(values: string[] = []): Record { + const entries = values.map(value => { + const index = value.indexOf('='); + if (index <= 0) throw new Error(`Expected KEY=VALUE, received "${value}"`); + return [value.slice(0, index), value.slice(index + 1)] as const; + }); + return Object.fromEntries(entries); +} + +function oauthOptions(options: any) { + if (![options.oauthClientId, options.oauthClientSecretEnv, options.oauthIssuer, options.oauthScope].some(value => value !== undefined)) return undefined; + if (!options.oauthClientId || !options.oauthClientSecretEnv || !options.oauthIssuer) { + throw new Error('OAuth requires --oauth-client-id, --oauth-client-secret-env and --oauth-issuer'); + } + return { type: 'client_credentials' as const, clientId: options.oauthClientId, clientSecretEnv: options.oauthClientSecretEnv, issuer: options.oauthIssuer, scope: options.oauthScope }; +} + // Helper function to make HTTP requests to daemon (bypassing proxy) function daemonRequest(method: string, path: string, body?: string): Promise<{ status: number; ok: boolean; data: any }> { return new Promise((resolve, reject) => { @@ -46,6 +63,7 @@ function daemonRequest(method: string, path: string, body?: string): Promise<{ s export const registerServerCommands = (program: Command) => { const listServersAction = () => { + try { const servers = configManager.listServers(); if (servers.length === 0) { console.log(chalk.yellow('No servers configured.')); @@ -116,37 +134,47 @@ export const registerServerCommands = (program: Command) => { console.log(''); console.log(chalk.cyan(`Total: ${servers.length} server(s)`)); console.log(''); + } catch (error: any) { + console.error(chalk.red(error.message)); + process.exitCode = 1; + } }; const addServerAction = (name: string, options: any) => { try { - if (options.type === 'sse' || options.type === 'http' || options.url) { + if (!['stdio', 'sse', 'http', 'streamableHttp'].includes(options.type)) throw new Error('Unknown server type'); + if (options.command && options.url) throw new Error('Specify command or url, not both'); + const auth = oauthOptions(options); + if (options.type !== 'stdio' || options.url) { if (!options.url) throw new Error(`URL is required for ${options.type || 'HTTP/SSE'} servers`); + if (options.env?.length || options.cwd || options.args?.length) throw new Error('env, cwd and args require a stdio server'); configManager.addServer(name, { url: options.url, + type: options.type === 'stdio' ? 'http' : options.type, + headers: options.header?.length ? parseAssignments(options.header) : undefined, + auth, + protocolVersion: options.protocolVersion, + disabled: options.disabled, }); } else { if (!options.command) throw new Error('Command is required for Stdio servers'); + if (options.header?.length || auth) throw new Error('Headers and OAuth require an HTTP/SSE server'); - const env: Record = {}; - if (options.env) { - options.env.forEach((e: string) => { - const parts = e.split('='); - const k = parts[0]; - const v = parts.slice(1).join('='); - if (k && v) env[k] = v; - }); - } + const env = parseAssignments(options.env); configManager.addServer(name, { command: options.command, args: options.args || [], env: Object.keys(env).length > 0 ? env : undefined, + cwd: options.cwd, + protocolVersion: options.protocolVersion, + disabled: options.disabled, }); } console.log(chalk.green(`Server "${name}" added successfully.`)); } catch (error: any) { console.error(chalk.red(`Error adding server: ${error.message}`)); + process.exitCode = 1; } }; @@ -156,6 +184,7 @@ export const registerServerCommands = (program: Command) => { console.log(chalk.green(`Server "${name}" removed.`)); } catch (error: any) { console.error(chalk.red(error.message)); + process.exitCode = 1; } }; @@ -165,6 +194,7 @@ export const registerServerCommands = (program: Command) => { console.log(chalk.green(`Server "${oldName}" renamed to "${newName}".`)); } catch (error: any) { console.error(chalk.red(error.message)); + process.exitCode = 1; } }; @@ -185,6 +215,7 @@ export const registerServerCommands = (program: Command) => { } catch (error: any) { console.error(chalk.red(`Failed to restart all servers: ${error.message}`)); console.error(chalk.yellow('Make sure the daemon is running (use: mcps start)')); + process.exitCode = 1; } return; } @@ -192,9 +223,24 @@ export const registerServerCommands = (program: Command) => { // Update specific server configuration try { const updates: any = {}; + if (options.disabled && options.enabled) throw new Error('Choose either --disabled or --enabled'); + const current = configManager.getServer(name); + if (!current) throw new Error(`Server with name "${name}" not found.`); + const transport = options.type ?? (options.url ? 'http' : options.command ? 'stdio' : detectServerType(current)); + const auth = oauthOptions(options); + if (transport !== 'stdio' && (options.env || options.cwd !== undefined || options.args)) throw new Error('env, cwd and args require a stdio server'); + if (transport === 'stdio' && (options.header || auth)) throw new Error('Headers and OAuth require an HTTP/SSE server'); if (options.command) updates.command = options.command; if (options.args) updates.args = options.args; if (options.url) updates.url = options.url; + if (options.type) updates.type = options.type; + if (options.cwd !== undefined) updates.cwd = options.cwd; + if (options.env) updates.env = { ...configManager.getServer(name)?.env as Record, ...parseAssignments(options.env) }; + if (options.header) updates.headers = { ...configManager.getServer(name)?.headers as Record, ...parseAssignments(options.header) }; + if (options.protocolVersion) updates.protocolVersion = options.protocolVersion; + if (auth) updates.auth = auth; + if (options.disabled !== undefined) updates.disabled = options.disabled; + if (options.enabled) updates.disabled = false; if (Object.keys(updates).length === 0) { console.log(chalk.yellow('No updates provided.')); @@ -207,6 +253,7 @@ export const registerServerCommands = (program: Command) => { console.log(chalk.gray('Note: Restart the daemon to apply changes: mcps restart')); } catch (error: any) { console.error(chalk.red(`Error updating server: ${error.message}`)); + process.exitCode = 1; } }; @@ -226,6 +273,14 @@ export const registerServerCommands = (program: Command) => { .option('--args [args...]', 'Arguments for the command', []) .option('--url ', 'URL for SSE/HTTP connection') .option('--env ', 'Environment variables (KEY=VALUE)', []) + .option('--header ', 'HTTP headers (KEY=VALUE)') + .option('--oauth-client-id ', 'OAuth client credentials ID') + .option('--oauth-client-secret-env ', 'Environment variable containing the OAuth secret') + .option('--oauth-issuer ', 'Authorization server issuer these credentials belong to') + .option('--oauth-scope ', 'OAuth scopes') + .option('--cwd ', 'Working directory for stdio server') + .option('--protocol-version ', 'auto, legacy, or 2026-07-28', 'auto') + .option('--disabled', 'Disable the server') .action(addServerAction); // Remove server command @@ -246,6 +301,17 @@ export const registerServerCommands = (program: Command) => { .option('--command ', 'New command') .option('--args [args...]', 'New arguments for the command') .option('--url ', 'New URL') + .option('--type ', 'New transport type') + .option('--env ', 'Merge environment variables (KEY=VALUE)') + .option('--header ', 'Merge HTTP headers (KEY=VALUE)') + .option('--oauth-client-id ', 'OAuth client credentials ID') + .option('--oauth-client-secret-env ', 'Environment variable containing the OAuth secret') + .option('--oauth-issuer ', 'Authorization server issuer these credentials belong to') + .option('--oauth-scope ', 'OAuth scopes') + .option('--cwd ', 'New stdio working directory') + .option('--protocol-version ', 'auto, legacy, or 2026-07-28') + .option('--disabled', 'Disable the server') + .option('--enabled', 'Enable the server') .action(updateServerAction); // ===== Legacy server subcommands (for backward compatibility) ===== @@ -265,6 +331,14 @@ export const registerServerCommands = (program: Command) => { .option('--args [args...]', 'Arguments for the command', []) .option('--url ', 'URL for SSE/HTTP connection') .option('--env ', 'Environment variables (KEY=VALUE)', []) + .option('--header ', 'HTTP headers (KEY=VALUE)') + .option('--oauth-client-id ', 'OAuth client credentials ID') + .option('--oauth-client-secret-env ', 'Environment variable containing the OAuth secret') + .option('--oauth-issuer ', 'Authorization server issuer these credentials belong to') + .option('--oauth-scope ', 'OAuth scopes') + .option('--cwd ', 'Working directory for stdio server') + .option('--protocol-version ', 'auto, legacy, or 2026-07-28', 'auto') + .option('--disabled', 'Disable the server') .action(addServerAction); serverCmd.command('remove ') @@ -282,5 +356,27 @@ export const registerServerCommands = (program: Command) => { .option('--command ', 'New command') .option('--args [args...]', 'New arguments for the command') .option('--url ', 'New URL') + .option('--type ', 'New transport type') + .option('--env ', 'Merge environment variables (KEY=VALUE)') + .option('--header ', 'Merge HTTP headers (KEY=VALUE)') + .option('--oauth-client-id ', 'OAuth client credentials ID') + .option('--oauth-client-secret-env ', 'Environment variable containing the OAuth secret') + .option('--oauth-issuer ', 'Authorization server issuer these credentials belong to') + .option('--oauth-scope ', 'OAuth scopes') + .option('--cwd ', 'New stdio working directory') + .option('--protocol-version ', 'auto, legacy, or 2026-07-28') + .option('--disabled', 'Disable the server') + .option('--enabled', 'Enable the server') .action(updateServerAction); + + const config = program.command('config').description('Inspect and validate the configuration file'); + config.command('path').action(() => console.log(configManager.getConfigPath())); + config.command('validate').action(() => { + try { + console.log(`Configuration valid: ${configManager.validateConfig()}`); + } catch (error: any) { + console.error(error.message); + process.exitCode = 1; + } + }); }; diff --git a/src/commands/tools.ts b/src/commands/tools.ts index b1d3143..c9f5b8e 100644 --- a/src/commands/tools.ts +++ b/src/commands/tools.ts @@ -59,14 +59,10 @@ export const registerToolsCommand = (program: Command) => { .option('-j, --json', 'Output raw JSON') .option('-t, --tool ', 'Filter tools by name(s)') .action(async (serverName, options) => { - // Check if server exists in config first - const serverConfig = configManager.getServer(serverName); - if (!serverConfig) { - console.error(chalk.red(`Server "${serverName}" not found in config.`)); - process.exit(1); - } - try { + const serverConfig = configManager.getServer(serverName); + if (!serverConfig) throw new Error(`Server "${serverName}" not found in config.`); + if (serverConfig.disabled) throw new Error(`Server "${serverName}" is disabled.`); // Auto-start daemon if needed await DaemonClient.ensureDaemon(); @@ -83,16 +79,15 @@ export const registerToolsCommand = (program: Command) => { ); } - if (!tools || tools.length === 0) { - console.log(chalk.yellow('No tools found.')); - return; - } - if (options.json) { // Raw JSON output console.log(JSON.stringify(tools, null, 2)); return; } + if (!tools || tools.length === 0) { + console.log(chalk.yellow('No tools found.')); + return; + } if (options.simple) { // Simple mode: only show tool names @@ -105,7 +100,7 @@ export const registerToolsCommand = (program: Command) => { } catch (error: any) { console.error(chalk.red(`Failed to list tools: ${error.message}`)); - process.exit(1); + process.exitCode = 1; } }); }; diff --git a/src/core/client.ts b/src/core/client.ts index 80420da..b63338a 100644 --- a/src/core/client.ts +++ b/src/core/client.ts @@ -1,304 +1,161 @@ -import { Client } from '@modelcontextprotocol/sdk/client/index.js'; -import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; -import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'; -import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; -import { ServerConfig, detectServerType } from '../types/config.js'; -import { EventSource } from 'eventsource'; -import { spawn } from 'child_process'; -import { exec } from 'child_process'; -import { promisify } from 'util'; -import fs from 'fs'; -import path from 'path'; - -const execAsync = promisify(exec); - -// 日志文件路径 -const logFile = path.join(process.env.HOME || '~', '.mcps', 'daemon.log'); - -// 日志函数(异步,避免阻塞) -const log = (message: string) => { - const timestamp = new Date().toISOString(); - const logMessage = `[${timestamp}] ${message}\n`; - try { - fs.appendFileSync(logFile, logMessage); - } catch (e) { - // 忽略日志写入错误 - } - try { - console.log(message); - } catch (e) { - // 忽略 console 错误 - } -}; - -// Required for SSEClientTransport in Node.js environment -// @ts-ignore -global.EventSource = EventSource; - -const resolveEnvPlaceholders = (input: string) => { +import { + Client, ClientCredentialsProvider, SSEClientTransport, StreamableHTTPClientTransport, + type CallToolRequestParams, type CompleteRequestParams, type GetPromptRequestParams, + type InputResponses, type RequestOptions, +} from '@modelcontextprotocol/client'; +import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'; +import { createRequire } from 'node:module'; +import { ServerConfig, StdioServerConfig, HttpServerConfig, detectServerType } from '../types/config.js'; + +const require = createRequire(import.meta.url); +const pkg = require('../../package.json'); + +export const resolveEnvPlaceholders = (input: string) => { const missing = new Set(); const resolved = input.replace(/\$\{([A-Za-z0-9_]+)\}|\$([A-Za-z0-9_]+)/g, (match, braced, bare) => { const key = braced || bare; - const val = process.env[key]; - if (val === undefined) { + if (process.env[key] === undefined) { missing.add(key); return match; } - return val; + return process.env[key]!; }); - if (missing.size > 0) { - const list = Array.from(missing).join(', '); - throw new Error(`Missing environment variables: ${list}`); - } + if (missing.size) throw new Error(`Missing environment variables: ${[...missing].join(', ')}`); return resolved; }; +export type Continuation = { inputResponses?: InputResponses; requestState?: string }; +export type ProtocolOperation = + 'info' | 'resources/list' | 'resources/templates/list' | 'resources/read' | + 'prompts/list' | 'prompts/get' | 'completion/complete'; + export class McpClientService { private client: Client | null = null; private transport: StdioClientTransport | SSEClientTransport | StreamableHTTPClientTransport | null = null; - private serverName: string = ''; - private serverType: string = ''; - private serverCommand: string = ''; - private serverArgs: string[] = []; - private daemonPid: number = process.pid; - private childPids: Set = new Set(); - private static globalPidsBeforeConnection: Set = new Set(); + private serverName = ''; - async connect(config: ServerConfig, serverName: string = '') { + async connect(config: ServerConfig, serverName = '') { + if (config.disabled) throw new Error(`Server "${serverName}" is disabled.`); this.serverName = serverName; const serverType = detectServerType(config); - this.serverType = serverType; - this.daemonPid = process.pid; - - try { - if (serverType === 'stdio' && 'command' in config) { - const stdioConfig = config as { command: string; args?: string[]; env?: Record }; - // 保存命令和参数用于后续清理进程 - this.serverCommand = stdioConfig.command; - this.serverArgs = stdioConfig.args || []; - - const resolvedConfigEnv: Record = {}; - if (stdioConfig.env) { - for (const key in stdioConfig.env) { - const val = stdioConfig.env[key]; - if (typeof val === 'string') { - resolvedConfigEnv[key] = resolveEnvPlaceholders(val); - } - } - } - - const rawEnv = stdioConfig.env ? { ...process.env, ...resolvedConfigEnv } : process.env; - const env: Record = {}; - for (const key in rawEnv) { - const val = rawEnv[key]; - if (typeof val === 'string') { - env[key] = val; - } - } - - const args = stdioConfig.args ? stdioConfig.args.map(arg => resolveEnvPlaceholders(arg)) : []; - this.transport = new StdioClientTransport({ - command: stdioConfig.command, - args, - env: env, + const configuredVersion = config.protocolVersion ?? 'auto'; + if (serverType === 'sse' && configuredVersion === '2026-07-28') { + throw new Error('MCP 2026-07-28 requires stdio or Streamable HTTP; legacy SSE cannot use this revision.'); + } + if (serverType === 'stdio' && 'command' in config) { + const stdio = config as StdioServerConfig; + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) if (value !== undefined) env[key] = value; + for (const [key, value] of Object.entries(stdio.env ?? {})) env[key] = resolveEnvPlaceholders(value); + this.transport = new StdioClientTransport({ + command: resolveEnvPlaceholders(stdio.command), + args: stdio.args?.map(resolveEnvPlaceholders), + cwd: stdio.cwd ? resolveEnvPlaceholders(stdio.cwd) : undefined, + env, + }); + } else if ('url' in config) { + const http = config as HttpServerConfig; + const headers = Object.fromEntries(Object.entries(http.headers ?? {}).map(([key, value]) => [key, resolveEnvPlaceholders(value)])); + const url = new URL(resolveEnvPlaceholders(http.url)); + const requestInit = Object.keys(headers).length ? { headers } : {}; + let authProvider: ClientCredentialsProvider | undefined; + if (http.auth) { + const secret = process.env[http.auth.clientSecretEnv]; + if (!secret) throw new Error(`Missing environment variable: ${http.auth.clientSecretEnv}`); + authProvider = new ClientCredentialsProvider({ + clientId: http.auth.clientId, clientSecret: secret, + expectedIssuer: http.auth.issuer, scope: http.auth.scope, }); - } else if (serverType === 'http' && 'url' in config) { - const httpConfig = config as { url: string; headers?: Record }; - const url = resolveEnvPlaceholders(httpConfig.url); - const requestInit: RequestInit = {}; - if (httpConfig.headers) { - const resolvedHeaders: Record = {}; - for (const key in httpConfig.headers) { - resolvedHeaders[key] = resolveEnvPlaceholders(httpConfig.headers[key]); - } - requestInit.headers = resolvedHeaders; - } - this.transport = new StreamableHTTPClientTransport(new URL(url), { requestInit }); - } else if ('url' in config) { - const sseConfig = config as { url: string; headers?: Record }; - const url = resolveEnvPlaceholders(sseConfig.url); - const requestInit: RequestInit = {}; - if (sseConfig.headers) { - const resolvedHeaders: Record = {}; - for (const key in sseConfig.headers) { - resolvedHeaders[key] = resolveEnvPlaceholders(sseConfig.headers[key]); - } - requestInit.headers = resolvedHeaders; - } - this.transport = new SSEClientTransport(new URL(url), { requestInit }); - } else { - throw new Error('Invalid server configuration: must have either command (for stdio) or url (for sse/http)'); } + this.transport = serverType === 'http' + ? new StreamableHTTPClientTransport(url, { requestInit, authProvider }) + : new SSEClientTransport(url, { requestInit, authProvider }); + } else { + throw new Error('Invalid server configuration: expected command or url.'); + } - this.client = new Client( - { - name: 'mcp-cli', - version: '1.0.0', - }, - { - capabilities: {}, - } - ); - + const mode = serverType === 'sse' ? 'legacy' : configuredVersion; + this.client = new Client({ name: 'mcps', version: pkg.version }, { + versionNegotiation: { + mode: mode === '2026-07-28' ? { pin: mode } : mode, + probe: { timeoutMs: 2000, maxRetries: 0 }, + }, + // CLI users explicitly supply continuation responses; never auto-accept a server's form or URL request. + capabilities: { elicitation: { form: {}, url: {} } }, + inputRequired: { autoFulfill: false }, + listChanged: { + tools: { onChanged: () => {} }, + resources: { onChanged: () => {} }, + prompts: { onChanged: () => {} }, + }, + }); + // Legacy servers use an unsolicited request instead of an input_required result. + // A background CLI daemon cannot collect consent interactively, so explicitly cancel it. + this.client.setRequestHandler('elicitation/create', async () => ({ action: 'cancel' })); + try { await this.client.connect(this.transport); - - // 连接成功后,立即查找并保存子进程 PID - if ('command' in config) { - await this.recordChildPids(); - } } catch (error) { - // Error will be handled by the caller + await this.close(); throw error; } } - // 记录子进程 PID(使用快照差异法) - private async recordChildPids() { - try { - // 获取连接前的所有子进程快照 - const getSnapshot = async (): Promise> => { - const pids = new Set(); - const getAllDescendants = async (parentPid: number): Promise => { - try { - const { stdout } = await execAsync(`pgrep -P ${parentPid}`); - const childPids = stdout.trim().split('\n').filter(pid => pid); - for (const pid of childPids) { - pids.add(parseInt(pid)); - await getAllDescendants(parseInt(pid)); - } - } catch { - // 没有子进程 - } - }; - await getAllDescendants(this.daemonPid); - return pids; - }; - - // 记录连接前的快照(第一次连接时为空) - const beforeSnapshot = new Set(McpClientService.globalPidsBeforeConnection); - - // 等待一小段时间,确保子进程完全启动 - await new Promise(resolve => setTimeout(resolve, 500)); - - // 获取连接后的快照 - const afterSnapshot = await getSnapshot(); - - // 找出差异(新启动的进程) - const newPids = new Set(); - for (const pid of afterSnapshot) { - if (!beforeSnapshot.has(pid)) { - newPids.add(pid); - } - } - - // 更新全局快照 - McpClientService.globalPidsBeforeConnection = afterSnapshot; - - // 过滤出匹配我们命令的进程 - const commandBaseName = this.serverCommand.split('/').pop() || this.serverCommand; - - const verbose = process.env.MCPS_VERBOSE === 'true'; - if (verbose) { - log(`[Daemon] ${this.serverName}: Found ${newPids.size} new PIDs: [${Array.from(newPids).join(', ')}]`); - } - - for (const pid of newPids) { - try { - const { stdout: cmdOutput } = await execAsync(`ps -p ${pid} -o command=`); - const cmdLine = cmdOutput.trim(); - - // 检查命令行是否匹配 - const isMatch = - cmdLine.includes(commandBaseName) || - cmdLine.includes('npm exec') || // npx 会转换成 npm exec - cmdLine.includes('npx') || - (this.serverArgs.length > 0 && this.serverArgs.some(arg => { - return cmdLine.includes(arg) && arg.length > 10; - })); - - if (isMatch) { - this.childPids.add(pid); - if (verbose) { - log(`[Daemon] ${this.serverName}: Added PID ${pid} to childPids (cmd: ${cmdLine.substring(0, 50)}...)`); - } - } - } catch { - // 进程可能已经不存在了 - } - } + private connected() { + if (!this.client) throw new Error('Client not connected'); + return this.client; + } - if (verbose) { - log(`[Daemon] ${this.serverName}: Total childPids after collection: ${this.childPids.size}`); - } - } catch (e) { - // 记录失败,不影响主流程 - console.error(`[Daemon] Failed to record child PIDs: ${e}`); - } + getInfo() { + const client = this.connected(); + return { + protocolVersion: client.getNegotiatedProtocolVersion(), + protocolEra: client.getProtocolEra(), + serverInfo: client.getServerVersion(), + capabilities: client.getServerCapabilities(), + instructions: client.getInstructions(), + discovery: client.getDiscoverResult(), + }; } async listTools() { - if (!this.client) throw new Error('Client not connected'); - return this.client.listTools(); + return this.connected().listTools(); } - async callTool(toolName: string, args: any, timeout?: number) { - if (!this.client) throw new Error('Client not connected'); - - // 记录工具调用请求 - log(`[Tool Request] Server: ${this.serverName}, Tool: ${toolName}, Args: ${JSON.stringify(args)}`); - - const options = timeout !== undefined ? { timeout } : undefined; - const result = await this.client.callTool({ - name: toolName, - arguments: args, - }, undefined, options); - - // 记录工具调用响应 - log(`[Tool Response] Server: ${this.serverName}, Tool: ${toolName}, Result: ${JSON.stringify(result)}`); - + async callTool(toolName: string, args: Record, timeout?: number, continuation: Continuation = {}) { + const options = { timeout, maxTotalTimeout: timeout, allowInputRequired: true }; + const params: CallToolRequestParams = { name: toolName, arguments: args, ...continuation }; + if (process.env.MCPS_VERBOSE === 'true') console.log(`[Tool Request] Server: ${this.serverName}, Tool: ${toolName}`); + const result = await this.connected().callTool(params, options); + if (process.env.MCPS_VERBOSE === 'true') console.log(`[Tool Response] Server: ${this.serverName}, Tool: ${toolName}`); return result; } - close() { - const verbose = process.env.MCPS_VERBOSE === 'true'; - - // 对于 stdio 类型的服务器,先杀掉子进程(在关闭 transport 之前) - if (this.serverType === 'stdio' && this.childPids.size > 0) { - const pidList = Array.from(this.childPids).join(', '); - if (verbose) { - log(`[Daemon] Closing ${this.serverName}, killing PIDs: [${pidList}]`); - } else { - // 简短版本,始终显示 - log(`[Daemon] Closing ${this.serverName} (${this.childPids.size} process(es))`); - } - - // 直接使用 SIGKILL,确保进程被终止 - for (const pid of this.childPids) { - try { - process.kill(pid, 'SIGKILL'); - if (verbose) { - log(`[Daemon] SIGKILLED child process ${pid} (${this.serverName})`); - } - } catch (e: any) { - if (verbose) { - log(`[Daemon] Failed to kill ${pid}: ${e.message}`); - } - } - } - - this.childPids.clear(); - if (verbose) { - log(`[Daemon] All child processes cleared for ${this.serverName}`); - } - } else { - if (verbose) { - log(`[Daemon] No child PIDs to kill for ${this.serverName} (childPids.size: ${this.childPids.size})`); - } + async request(operation: ProtocolOperation, params: Record = {}, timeout?: number) { + const client = this.connected(); + const options: RequestOptions = { timeout, maxTotalTimeout: timeout, allowInputRequired: true }; + switch (operation) { + case 'info': return this.getInfo(); + case 'resources/list': return client.listResources(); + case 'resources/templates/list': return client.listResourceTemplates(); + case 'resources/read': + if (typeof params.uri !== 'string') throw new Error('Resource uri must be a string'); + return client.readResource({ uri: params.uri, ...params }, options); + case 'prompts/list': return client.listPrompts(); + case 'prompts/get': + if (typeof params.name !== 'string') throw new Error('Prompt name must be a string'); + return client.getPrompt(params as GetPromptRequestParams, options); + case 'completion/complete': return client.complete(params as CompleteRequestParams, options); + default: throw new Error(`Unsupported MCP operation: ${operation}`); } + } - // 暂时不关闭 transport,避免卡住 - if (verbose) { - log(`[Daemon] ${this.serverName} close() completed`); - } + async close() { + const client = this.client; + const transport = this.transport; + this.client = null; + this.transport = null; + // The SDK owns and reaps the exact stdio child; avoid matching/killing unrelated PIDs. + if (client) await client.close(); + else if (transport) await transport.close(); } } diff --git a/src/core/config.ts b/src/core/config.ts index 211be00..399c135 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -1,9 +1,12 @@ -import fs from 'fs'; -import path from 'path'; -import os from 'os'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { randomUUID } from 'node:crypto'; import { Config, ConfigSchema, ServerConfig, ServerConfigSchema } from '../types/config.js'; const getDefaultConfigDir = () => process.env.MCPS_CONFIG_DIR || path.join(os.homedir(), '.mcps'); +const isObject = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); export class ConfigManager { private configDir: string; @@ -14,145 +17,126 @@ export class ConfigManager { this.configFile = path.join(this.configDir, 'mcp.json'); } + getConfigPath() { return this.configFile; } + private ensureConfigDir() { - if (!fs.existsSync(this.configDir)) { - fs.mkdirSync(this.configDir, { recursive: true }); - } + fs.mkdirSync(this.configDir, { recursive: true, mode: 0o700 }); } - private loadConfig(): Config { - this.ensureConfigDir(); - if (!fs.existsSync(this.configFile)) { - return { mcpServers: {} }; - } + private loadConfig(forWrite = false): Config { + if (!fs.existsSync(this.configFile)) return { mcpServers: {} }; + let json: unknown; try { - const content = fs.readFileSync(this.configFile, 'utf-8'); - const json = JSON.parse(content); - - if (!json || typeof json !== 'object') { - console.warn('Invalid config file structure. Expected JSON object.'); - return { mcpServers: {} }; - } - - // Only accept standard MCP format: { mcpServers: { ... } } - if (!json.mcpServers || typeof json.mcpServers !== 'object') { - console.warn('Invalid config format. Expected { mcpServers: { ... } }'); - return { mcpServers: {} }; - } - - // Validate each server config - const validServers: Record = {}; - for (const [name, serverConfig] of Object.entries(json.mcpServers)) { - const result = ServerConfigSchema.safeParse(serverConfig); - if (result.success) { - validServers[name] = result.data; - } else { - console.warn(`Skipping invalid server config "${name}":`, result.error.errors[0]?.message); - } - } - - return { mcpServers: validServers }; + json = JSON.parse(fs.readFileSync(this.configFile, 'utf8')); } catch (error) { - console.error('Failed to parse config file:', error); + const reason = (error as NodeJS.ErrnoException).code ?? 'Invalid JSON'; + throw new Error(`Cannot read configuration ${this.configFile}: ${reason}. Original file was not changed.`); + } + if (!isObject(json) || !isObject(json.mcpServers)) { + const message = 'Invalid config format. Expected { mcpServers: { ... } }'; + if (forWrite) throw new Error(`${message}. Original file was not changed.`); + console.warn(message); return { mcpServers: {} }; } + const validServers: Record = Object.create(null); + for (const [name, server] of Object.entries(json.mcpServers)) { + const result = ServerConfigSchema.safeParse(server); + if (!result.success) { + const message = `Invalid server config "${name}": ${result.error.issues[0]?.message}`; + if (forWrite) throw new Error(`${message}. Original file was not changed.`); + console.warn(`Skipping ${message}`); + } else { + validServers[name] = result.data; + } + } + return ConfigSchema.parse({ ...json, mcpServers: validServers }); } - private saveConfig(config: Config) { + validateConfig() { + this.loadConfig(true); + return this.configFile; + } + + private mutate(change: (config: Config) => void) { this.ensureConfigDir(); - fs.writeFileSync(this.configFile, JSON.stringify(config, null, 2), 'utf-8'); + const lockPath = `${this.configFile}.lock`; + let lock: number; + try { + lock = fs.openSync(lockPath, 'wx', 0o600); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') { + throw new Error(`Configuration is being updated (${lockPath}). Retry after the other writer finishes.`); + } + throw error; + } + const temporary = `${this.configFile}.${randomUUID()}.tmp`; + try { + const config = this.loadConfig(true); + change(config); + const validated = ConfigSchema.parse(config); + const mode = fs.existsSync(this.configFile) ? fs.statSync(this.configFile).mode & 0o777 : 0o600; + fs.writeFileSync(temporary, JSON.stringify(validated, null, 2) + '\n', { mode, flag: 'wx' }); + fs.renameSync(temporary, this.configFile); + } finally { + if (fs.existsSync(temporary)) fs.unlinkSync(temporary); + fs.closeSync(lock); + fs.unlinkSync(lockPath); + } } listServers(): Array { - const config = this.loadConfig(); - return Object.entries(config.mcpServers).map(([name, server]) => ({ - name, - ...server, - })); + return Object.entries(this.loadConfig().mcpServers).map(([name, server]) => ({ ...server, name })); } getServer(name: string): (ServerConfig & { name: string }) | undefined { - const config = this.loadConfig(); - const server = config.mcpServers[name]; - if (!server) return undefined; - return { name, ...server }; + const servers = this.loadConfig().mcpServers; + return Object.hasOwn(servers, name) ? { ...servers[name], name } : undefined; } addServer(name: string, server: ServerConfig) { - const config = this.loadConfig(); - if (config.mcpServers[name]) { - throw new Error(`Server with name "${name}" already exists.`); - } - config.mcpServers[name] = server; - this.saveConfig(config); + const validated = ServerConfigSchema.parse(server); + this.mutate(config => { + if (Object.hasOwn(config.mcpServers, name)) throw new Error(`Server with name "${name}" already exists.`); + Object.defineProperty(config.mcpServers, name, { value: validated, enumerable: true, writable: true, configurable: true }); + }); } removeServer(name: string) { - const config = this.loadConfig(); - if (!config.mcpServers[name]) { - throw new Error(`Server with name "${name}" not found.`); - } - delete config.mcpServers[name]; - this.saveConfig(config); + this.mutate(config => { + if (!Object.hasOwn(config.mcpServers, name)) throw new Error(`Server with name "${name}" not found.`); + delete config.mcpServers[name]; + }); } renameServer(oldName: string, newName: string) { - const config = this.loadConfig(); - const current = config.mcpServers[oldName]; - if (!current) { - throw new Error(`Server with name "${oldName}" not found.`); - } - if (config.mcpServers[newName]) { - throw new Error(`Server with name "${newName}" already exists.`); - } - - // Insert newName in the same position as oldName, preserving key order - const newServers: Record = {}; - for (const [key, value] of Object.entries(config.mcpServers)) { - if (key === oldName) { - newServers[newName] = value; - } else { - newServers[key] = value; - } - } - - config.mcpServers = newServers; - this.saveConfig(config); + this.mutate(config => { + if (!Object.hasOwn(config.mcpServers, oldName)) throw new Error(`Server with name "${oldName}" not found.`); + if (Object.hasOwn(config.mcpServers, newName)) throw new Error(`Server with name "${newName}" already exists.`); + config.mcpServers = Object.fromEntries(Object.entries(config.mcpServers).map(([key, value]) => [key === oldName ? newName : key, value])); + }); } updateServer(name: string, updates: Partial) { - const config = this.loadConfig(); - const current = config.mcpServers[name]; - if (!current) { - throw new Error(`Server with name "${name}" not found.`); - } - - const updated = { ...current, ...updates }; - const result = ServerConfigSchema.safeParse(updated); - if (!result.success) { - throw new Error(`Invalid update: ${result.error.message}`); - } - - config.mcpServers[name] = result.data; - this.saveConfig(config); + this.mutate(config => { + if (!Object.hasOwn(config.mcpServers, name)) throw new Error(`Server with name "${name}" not found.`); + const updated: Record = { ...config.mcpServers[name], ...updates }; + if ('url' in updates) { + delete updated.command; delete updated.args; delete updated.env; delete updated.cwd; + if (!('type' in updates)) delete updated.type; + } else if ('command' in updates) { + delete updated.url; delete updated.headers; delete updated.auth; + if (!('type' in updates)) updated.type = 'stdio'; + } + const result = ServerConfigSchema.safeParse(updated); + if (!result.success) throw new Error(`Invalid update: ${result.error.message}`); + config.mcpServers[name] = result.data; + }); } getDaemonTimeout(): number { - // Priority: environment variable > config file > default - const envTimeout = process.env.MCPS_DAEMON_TIMEOUT; - if (envTimeout) { - const parsed = parseInt(envTimeout, 10); - if (!isNaN(parsed) && parsed > 0) { - return parsed * 1000; // Convert seconds to milliseconds - } - } - - const config = this.loadConfig(); - if (config.daemonTimeout) { - return config.daemonTimeout; - } - - return 20000; // Default 20 seconds + const env = process.env.MCPS_DAEMON_TIMEOUT; + if (env && /^\d+$/.test(env) && Number(env) > 0) return Number(env) * 1000; + return this.loadConfig().daemonTimeout ?? 20000; } } diff --git a/src/core/daemon-client.ts b/src/core/daemon-client.ts index faa21fc..e68cd13 100644 --- a/src/core/daemon-client.ts +++ b/src/core/daemon-client.ts @@ -1,83 +1,78 @@ -import { spawn } from 'child_process'; -import chalk from 'chalk'; -import { DAEMON_BASE_URL } from './constants.js'; +import { spawn } from 'node:child_process'; +import http from 'node:http'; +import { DAEMON_PORT } from './constants.js'; import { configManager } from './config.js'; +import { type Continuation, type ProtocolOperation } from './client.js'; + +export async function daemonRequest(method: string, endpoint: string, body?: unknown, port = DAEMON_PORT, timeout = 300000): Promise { + return new Promise((resolve, reject) => { + const request = http.request({ hostname: '127.0.0.1', port, path: endpoint, method, headers: { 'Content-Type': 'application/json' } }, response => { + let data = ''; + response.setEncoding('utf8'); + response.on('data', chunk => { data += chunk; }); + response.on('error', reject); + response.on('end', () => { + try { + const parsed = JSON.parse(data); + if ((response.statusCode ?? 500) >= 400) { + const error = new Error(parsed.error ?? 'Daemon request failed'); + Object.assign(error, { code: parsed.code, data: parsed.data }); + reject(error); + } else resolve(parsed); + } catch (error) { reject(error); } + }); + }); + request.setTimeout(timeout, () => request.destroy(new Error('Daemon request timed out'))); + request.on('error', reject); + if (body !== undefined) request.write(JSON.stringify(body)); + request.end(); + }); +} export class DaemonClient { static async isRunning(): Promise { try { - const res = await fetch(`${DAEMON_BASE_URL}/status`); - return res.ok; - } catch { - return false; - } + const status = await daemonRequest('GET', '/status', undefined, DAEMON_PORT, 2000); + return status.status === 'running' && status.configPath === configManager.getConfigPath(); + } catch { return false; } } - static async startDaemon(timeout?: number): Promise { - console.log(chalk.gray('Starting background daemon...')); - - // Get timeout from parameter or config - const daemonTimeout = timeout || configManager.getDaemonTimeout(); - - // Use process.argv[1] which points to the CLI entry point - // detached: true allows the child to keep running after parent exits - const subprocess = spawn(process.execPath, [process.argv[1], 'daemon', 'start'], { - detached: true, - stdio: 'ignore', - env: process.env + static async startDaemon(timeout = configManager.getDaemonTimeout()): Promise { + console.error('Starting background daemon...'); + const subprocess = spawn(process.execPath, [...process.execArgv, process.argv[1], 'start'], { + detached: true, stdio: 'ignore', env: process.env, }); - subprocess.unref(); - - // Wait for daemon to be ready - const start = Date.now(); - while (Date.now() - start < daemonTimeout) { - if (await this.isRunning()) { - return; + const started = Date.now(); + while (Date.now() - started < timeout) { + try { + const status = await daemonRequest('GET', '/status', undefined, DAEMON_PORT, 1000); + if (status.configPath !== configManager.getConfigPath()) throw new Error('This daemon port belongs to a different configuration. Choose a different MCPS_PORT.'); + if (status.status === 'running' && status.initialized) return; + } catch (error) { + if (error instanceof Error && error.message.includes('different configuration')) throw error; } - await new Promise(resolve => setTimeout(resolve, 200)); + await new Promise(resolve => setTimeout(resolve, 100)); } - - throw new Error(`Daemon failed to start within ${daemonTimeout / 1000}s timeout`); + throw new Error(`Daemon failed to initialize within ${timeout / 1000}s. Inspect the daemon logs.`); } - static async ensureDaemon(timeout?: number): Promise { - if (await this.isRunning()) { - return; - } - await this.startDaemon(timeout); + static async ensureDaemon(timeout?: number) { + if (!await this.isRunning()) await this.startDaemon(timeout); } - static async executeTool(serverName: string, toolName: string, args: any, timeout?: number) { - const response = await fetch(`${DAEMON_BASE_URL}/call`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ server: serverName, tool: toolName, args, timeout }), - }); - - if (!response.ok) { - const err = await response.json(); - throw new Error(err.error || 'Daemon error'); - } - - const data = await response.json(); - return data.result; + static async executeTool(server: string, tool: string, args: any, timeout?: number, continuation: Continuation = {}) { + const response = await daemonRequest('POST', '/call', { server, tool, args, timeout, ...continuation }, DAEMON_PORT, (timeout ?? 300000) + 5000); + return response.result; } - static async listTools(serverName: string) { - const response = await fetch(`${DAEMON_BASE_URL}/list`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ server: serverName }), - }); - - if (!response.ok) { - const err = await response.json(); - throw new Error(err.error || 'Daemon error'); - } + static async listTools(server: string) { + const response = await daemonRequest('POST', '/list', { server }); + return response.tools; + } - const data = await response.json(); - // The daemon returns { tools: [...] } - return data.tools || []; + static async request(server: string, operation: ProtocolOperation, params: Record = {}, timeout = 300000) { + const response = await daemonRequest('POST', '/protocol', { server, operation, params, timeout }, DAEMON_PORT, timeout + 5000); + return response.result; } } diff --git a/src/core/pool.ts b/src/core/pool.ts index 634f331..7cd6b71 100644 --- a/src/core/pool.ts +++ b/src/core/pool.ts @@ -1,61 +1,67 @@ import { McpClientService } from './client.js'; import { configManager } from './config.js'; -import { ServerConfig } from '../types/config.js'; export class ConnectionPool { private clients: Map = new Map(); - private toolsCache: Map = new Map(); // Cache full tools result + private pending = new Map>(); + private connectingClients = new Map(); + private failures = new Map(); private initializing = false; private initialized = false; async getClient(serverName: string, options?: { timeoutMs?: number }): Promise { - if (this.clients.has(serverName)) { - return this.clients.get(serverName)!; - } - const serverConfig = configManager.getServer(serverName); if (!serverConfig) { throw new Error(`Server "${serverName}" not found in config.`); } + if (serverConfig.disabled) throw new Error(`Server "${serverName}" is disabled.`); + if (this.clients.has(serverName)) return this.clients.get(serverName)!; + if (this.pending.has(serverName)) return this.pending.get(serverName)!; const client = new McpClientService(); - const connectPromise = client.connect(serverConfig); - if (options?.timeoutMs) { - const timeoutPromise = new Promise((_, reject) => { - setTimeout(() => reject(new Error(`Connection timeout after ${options.timeoutMs}ms`)), options.timeoutMs); - }); - await Promise.race([connectPromise, timeoutPromise]); - } else { - await connectPromise; - } - this.clients.set(serverName, client); - - // Cache full tools result after connection - try { - const result = await client.listTools(); - this.toolsCache.set(serverName, result.tools || []); - } catch (e) { - // Connection succeeded but listTools failed, cache as empty array - this.toolsCache.set(serverName, []); - } - - return client; - } - - getCachedTools(serverName: string): any[] | null { - return this.toolsCache.has(serverName) ? this.toolsCache.get(serverName)! : null; + this.connectingClients.set(serverName, client); + const connecting = (async () => { + let timer: ReturnType | undefined; + try { + const connection = client.connect(serverConfig, serverName); + if (options?.timeoutMs) { + await Promise.race([connection, new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`Connection timeout after ${options.timeoutMs}ms`)), options.timeoutMs); + })]); + } else await connection; + if (this.connectingClients.get(serverName) !== client) throw new Error('Connection was reset while connecting'); + this.clients.set(serverName, client); + this.failures.delete(serverName); + return client; + } catch (error) { + if (this.connectingClients.get(serverName) === client) this.failures.set(serverName, error instanceof Error ? error.message : String(error)); + await client.close(); + throw error; + } finally { + if (timer) clearTimeout(timer); + if (this.connectingClients.get(serverName) === client) { + this.pending.delete(serverName); + this.connectingClients.delete(serverName); + } + } + })(); + this.pending.set(serverName, connecting); + return connecting; } async closeClient(serverName: string) { - if (this.clients.has(serverName)) { + const client = this.clients.get(serverName) ?? this.connectingClients.get(serverName); + this.clients.delete(serverName); + this.connectingClients.delete(serverName); + this.pending.delete(serverName); + this.failures.delete(serverName); + if (client) { console.log(`[Daemon] Closing connection to ${serverName}...`); try { - await this.clients.get(serverName)!.close(); + await client.close(); } catch (e) { console.error(`[Daemon] Error closing ${serverName}:`, e); } - this.clients.delete(serverName); - this.toolsCache.delete(serverName); return true; } return false; @@ -66,16 +72,19 @@ export class ConnectionPool { if (verbose) { console.log('closeAll() called'); } - for (const [name, client] of this.clients) { + const closing = new Map([...this.connectingClients, ...this.clients]); + this.clients.clear(); + this.connectingClients.clear(); + this.pending.clear(); + this.failures.clear(); + for (const [name, client] of closing) { console.log(`Closing connection to ${name}...`); try { - client.close(); + await client.close(); } catch (e) { console.error(`Error closing ${name}:`, e); } } - this.clients.clear(); - this.toolsCache.clear(); if (verbose) { console.log('Connection pools cleared'); } @@ -89,7 +98,8 @@ export class ConnectionPool { const verbose = process.env.MCPS_VERBOSE === 'true'; // 获取连接超时时间(从环境变量或默认 20 秒) - const connectionTimeout = parseInt(process.env.MCPS_CONNECTION_TIMEOUT || '20000', 10); + const configuredTimeout = Number(process.env.MCPS_CONNECTION_TIMEOUT ?? 20000); + const connectionTimeout = Number.isFinite(configuredTimeout) && configuredTimeout > 0 ? configuredTimeout : 20000; // 过滤掉 disabled 的服务器 const enabledServers = servers.filter(server => { @@ -156,30 +166,24 @@ export class ConnectionPool { return { initializing: this.initializing, initialized: this.initialized }; } - async getActiveConnectionDetails(includeTools = true): Promise<{ name: string, toolsCount: number | null, status: string }[]> { + async getActiveConnectionDetails(includeTools = true) { const details = []; for (const [name, client] of this.clients) { let toolsCount = null; let status = 'connected'; if (includeTools) { - // Use cached tools count instead of calling listTools again - if (this.toolsCache.has(name)) { - toolsCount = this.toolsCache.get(name)!.length; - } else { - // Fallback: if not cached, fetch it now - try { - const result = await client.listTools(); - toolsCount = result.tools.length; - this.toolsCache.set(name, result.tools || []); - } catch (e) { - status = 'error'; - } + try { + const result = await client.listTools(); + toolsCount = result.tools.length; + } catch { + status = 'error'; } } - details.push({ name, toolsCount, status }); + details.push({ name, toolsCount, status, ...client.getInfo() }); } + for (const [name, error] of this.failures) details.push({ name, toolsCount: null, status: 'error', error }); return details; } } diff --git a/src/index.ts b/src/index.ts index 89c9200..3b4ede1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,6 +4,7 @@ import { registerServerCommands } from './commands/server.js'; import { registerToolsCommand } from './commands/tools.js'; import { registerCallCommand } from './commands/call.js'; import { registerDaemonCommand } from './commands/daemon.js'; +import { registerProtocolCommands } from './commands/protocol.js'; import { createRequire } from 'module'; const require = createRequire(import.meta.url); @@ -20,5 +21,6 @@ registerServerCommands(program); registerToolsCommand(program); registerCallCommand(program); registerDaemonCommand(program); +registerProtocolCommands(program); -program.parse(process.argv); +await program.parseAsync(process.argv); diff --git a/src/tests/fixtures/mcp-server.mjs b/src/tests/fixtures/mcp-server.mjs new file mode 100644 index 0000000..4a1bf16 --- /dev/null +++ b/src/tests/fixtures/mcp-server.mjs @@ -0,0 +1,141 @@ +import http from 'node:http'; +import fs from 'node:fs'; +import { McpServer, ResourceTemplate, completable, createMcpHandler, inputRequired } from '@modelcontextprotocol/server'; +import { serveStdio } from '@modelcontextprotocol/server/stdio'; +import { toNodeHandler } from '@modelcontextprotocol/node'; +import * as z from 'zod/v4'; + +const [transport = 'stdio', era = 'modern'] = process.argv.slice(2); +let toolAdded = false; +const echo = text => ({ text, cwd: process.cwd(), empty: process.env.FIXTURE_EMPTY ?? 'unset', pid: process.pid }); +const definitions = [ + { name: 'echo', description: 'Echo with process context', inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] } }, + { name: 'rich', description: 'Modern content and array output', inputSchema: { type: 'object' }, outputSchema: { type: 'array', items: { type: 'number' } } }, + { name: 'fail', inputSchema: { type: 'object' } }, + { name: 'confirm', inputSchema: { type: 'object' } }, + { name: 'add_tool', inputSchema: { type: 'object' } }, +]; + +function factory() { + const server = new McpServer({ name: 'mcps-protocol-fixture', version: '1.0.0' }, { + requestState: { verify: value => { + if (value !== 'approval-step') throw new Error('Invalid request state'); + return { step: 'approval' }; + } }, + }); + server.registerTool('echo', { inputSchema: z.object({ text: z.string() }) }, async ({ text }) => ({ + content: [{ type: 'text', text: JSON.stringify(echo(text)) }], + structuredContent: echo(text), + })); + server.registerTool('rich', { outputSchema: z.array(z.number()) }, async () => ({ + content: [ + { type: 'audio', mimeType: 'audio/wav', data: 'YXVkaW8=' }, + { type: 'resource_link', name: 'document', uri: 'fixture://document', description: 'Test document' }, + { type: 'resource', resource: { uri: 'fixture://embedded', mimeType: 'text/plain', text: 'embedded text' } }, + ], + structuredContent: [1, 2, 3], + _meta: { 'org.example/fixture': true }, + })); + server.registerTool('fail', {}, async () => ({ isError: true, content: [{ type: 'text', text: 'deliberate tool failure' }] })); + server.registerTool('confirm', { inputSchema: z.object({}) }, async (_args, ctx) => { + const response = ctx.mcpReq.inputResponses?.approval; + if (!response) return inputRequired({ + inputRequests: { approval: inputRequired.elicit({ message: 'Approve this fixture action?', requestedSchema: z.object({ approved: z.boolean() }) }) }, + requestState: 'approval-step', + }); + const state = ctx.mcpReq.requestState(); + if (state?.step !== 'approval') throw new Error('Continuation state was not preserved'); + return { content: [{ type: 'text', text: response.action === 'accept' && response.content?.approved === true ? 'approved' : 'declined' }] }; + }); + const add = () => server.registerTool('added', {}, async () => ({ content: [{ type: 'text', text: 'new tool' }] })); + if (toolAdded) add(); + server.registerTool('add_tool', {}, async () => { + if (!toolAdded) { toolAdded = true; add(); } + return { content: [{ type: 'text', text: 'added' }] }; + }); + // Exercise actual cursor pagination, rather than returning a single in-memory list. + server.server.setRequestHandler('tools/list', async request => { + const all = toolAdded ? [...definitions, { name: 'added', inputSchema: { type: 'object' } }] : definitions; + return request.params?.cursor ? { tools: all.slice(2) } : { tools: all.slice(0, 2), nextCursor: 'page-2' }; + }); + server.registerResource('document', 'fixture://document', { mimeType: 'text/plain' }, async uri => ({ + contents: [{ uri: uri.href, mimeType: 'text/plain', text: 'fixture document' }], + })); + server.registerResource('item', new ResourceTemplate('fixture://items/{name}', { list: undefined }), {}, async (uri, variables) => ({ + contents: [{ uri: uri.href, text: String(variables.name) }], + })); + server.registerPrompt('welcome', { argsSchema: z.object({ + name: completable(z.string(), value => ['Taipei', 'Tokyo'].filter(city => city.startsWith(value))), + }) }, async ({ name }) => ({ messages: [{ role: 'user', content: { type: 'text', text: 'Hello ' + name } }] })); + return server; +} + +async function legacyFactory() { + const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js'); + const server = new McpServer({ name: 'mcps-legacy-fixture', version: '1.0.0' }); + server.registerTool('echo', { inputSchema: { text: z.string() } }, async ({ text }) => ({ + content: [{ type: 'text', text: JSON.stringify(echo(text)) }], + })); + server.registerTool('confirm', { inputSchema: {} }, async () => { + const result = await server.server.elicitInput({ message: 'Legacy approval?', requestedSchema: { type: 'object', properties: { approved: { type: 'boolean' } } } }); + return { content: [{ type: 'text', text: result.action }] }; + }); + return server; +} + +if (transport === 'stdio') { + if (era === 'legacy') { + const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js'); + await (await legacyFactory()).connect(new StdioServerTransport()); + } else serveStdio(factory); +} else if (transport === 'http') { + const handler = createMcpHandler(factory); + const listener = toNodeHandler(handler); + const server = http.createServer(async (request, response) => { + const base = 'http://127.0.0.1:' + server.address().port; + const json = value => { response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify(value)); }; + if (request.url?.startsWith('/.well-known/oauth-protected-resource')) { + json({ resource: base + '/oauth/mcp', authorization_servers: [base + '/issuer'], scopes_supported: ['mcp:read'] }); return; + } + if (request.url?.includes('.well-known/oauth-authorization-server') || request.url?.includes('.well-known/openid-configuration')) { + json({ issuer: base + '/issuer', authorization_endpoint: base + '/authorize', token_endpoint: base + '/token', response_types_supported: ['code'], grant_types_supported: ['client_credentials'], token_endpoint_auth_methods_supported: ['client_secret_basic'] }); return; + } + if (request.url === '/token') { + let body = ''; + for await (const chunk of request) body += chunk.toString(); + if (request.headers.authorization !== 'Basic ' + Buffer.from('fixture-client:fixture-secret').toString('base64') || new URLSearchParams(body).get('grant_type') !== 'client_credentials') { + response.statusCode = 401; json({ error: 'invalid_client' }); return; + } + json({ access_token: 'fixture-access-token', token_type: 'Bearer', expires_in: 3600, scope: 'mcp:read' }); return; + } + if (request.url === '/oauth/mcp' && request.headers.authorization !== 'Bearer fixture-access-token') { + response.setHeader('WWW-Authenticate', 'Bearer resource_metadata="' + base + '/.well-known/oauth-protected-resource/oauth/mcp"'); + response.statusCode = 401; json({ error: 'unauthorized' }); return; + } + if (request.url === '/denied') { response.writeHead(401); response.end(); return; } + if (process.env.FIXTURE_REQUEST_LOG && request.method === 'POST') { + // Capture non-secret wire metadata for protocol conformance assertions. + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + const bytes = Buffer.concat(chunks); + const body = JSON.parse(bytes.toString()); + fs.appendFileSync(process.env.FIXTURE_REQUEST_LOG, JSON.stringify({ method: body.method, meta: body.params?._meta, protocolHeader: request.headers['mcp-protocol-version'], sessionHeader: request.headers['mcp-session-id'], authorization: request.headers['x-fixture-token'] }) + '\n'); + request.body = body; + // The Node adapter accepts a pre-parsed body as its third argument. + await listener(request, response, body); + } else await listener(request, response); + }); + server.listen(0, '127.0.0.1', () => console.log(JSON.stringify({ port: server.address().port }))); +} else if (transport === 'sse') { + const { SSEServerTransport } = await import('@modelcontextprotocol/sdk/server/sse.js'); + let channel; + const server = http.createServer(async (request, response) => { + if (request.url === '/events' && request.method === 'GET') { + channel = new SSEServerTransport('/messages', response); + await (await legacyFactory()).connect(channel); + } else if (request.url?.startsWith('/messages') && request.method === 'POST' && channel) { + await channel.handlePostMessage(request, response); + } else { response.writeHead(404); response.end(); } + }); + server.listen(0, '127.0.0.1', () => console.log(JSON.stringify({ port: server.address().port }))); +} diff --git a/src/tests/global-setup.ts b/src/tests/global-setup.ts new file mode 100644 index 0000000..316e2f4 --- /dev/null +++ b/src/tests/global-setup.ts @@ -0,0 +1,6 @@ +import { execFileSync } from 'node:child_process'; + +export default function setup() { + // Subprocess integration tests must exercise freshly compiled CLI code. + execFileSync(process.execPath, ['node_modules/typescript/bin/tsc'], { stdio: 'inherit' }); +} diff --git a/src/tests/integration/cli.test.ts b/src/tests/integration/cli.test.ts new file mode 100644 index 0000000..2e86658 --- /dev/null +++ b/src/tests/integration/cli.test.ts @@ -0,0 +1,117 @@ +import { beforeAll, afterAll, describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { fixture, repository, runCli, startFixture, stopFixture, freePort, waitForDaemonExit } from './helpers.js'; + +describe('CLI to daemon to real MCP servers', () => { + let directory: string; + let port: number; + let env: Record; + let daemon: ChildProcess; + let remote: Awaited>; + beforeAll(async () => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mcps-cli-integration-')); + port = await freePort(); + remote = await startFixture('http'); + env = { MCPS_CONFIG_DIR: directory, MCPS_PORT: String(port), MCPS_DAEMON_TIMEOUT: '10' }; + fs.writeFileSync(path.join(directory, 'mcp.json'), JSON.stringify({ daemonTimeout: 10000, mcpServers: { + stdio: { command: process.execPath, args: [fixture], cwd: directory, env: { FIXTURE_EMPTY: '' } }, + legacy: { command: process.execPath, args: [fixture, 'stdio', 'legacy'] }, + remote: { url: remote.url, type: 'http' }, + } })); + daemon = spawn(process.execPath, ['dist/index.js', 'start'], { cwd: repository, env: { ...process.env, ...env, MCPS_DAEMON_DETACHED: 'true' }, stdio: 'ignore' }); + for (let attempt = 0; attempt < 80; attempt++) { + if (daemon.exitCode !== null) throw new Error('Integration daemon exited before readiness'); + const status = await fetch('http://127.0.0.1:' + port + '/status').then(response => response.json(), () => null); + if (status?.initialized && status.connections.length === 3) return; + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error('Integration daemon did not become ready'); + }); + afterAll(async () => { + if (daemon && daemon.exitCode === null) { + await runCli(['stop'], env); + await waitForDaemonExit(port); + await stopFixture(daemon); + } + if (remote) await stopFixture(remote.child); + if (directory) fs.rmSync(directory, { recursive: true, force: true }); + }); + const run = (...args: string[]) => runCli(args, env); + it('reports negotiated modern and legacy protocols through real status/discover commands', async () => { + const status = await run('status', '--json'); + expect(status.code).toBe(0); + expect(JSON.parse(status.stdout).connections).toEqual(expect.arrayContaining([ + expect.objectContaining({ name: 'stdio', protocolVersion: '2026-07-28' }), + expect.objectContaining({ name: 'legacy', protocolVersion: '2025-11-25' }), + ])); + const discover = await run('discover', 'remote'); + expect(JSON.parse(discover.stdout)).toMatchObject({ protocolEra: 'modern', protocolVersion: '2026-07-28' }); + }); + it('honors --port even when MCPS_PORT names another port', async () => { + const result = await runCli(['status', '--port', String(port), '--json'], { ...env, MCPS_PORT: '1' }); + expect(result.code).toBe(0); + expect(JSON.parse(result.stdout).status).toBe('running'); + }); + it('executes actual CLI calls with parseable full JSON results', async () => { + const result = await run('call', 'stdio', 'echo', 'text=hello', '--output-json'); + expect(result.code).toBe(0); + expect(JSON.parse(result.stdout).structuredContent).toMatchObject({ text: 'hello', cwd: directory, empty: '' }); + const rich = await run('call', 'remote', 'rich', '--output-json'); + expect(rich.code).toBe(0); + expect(JSON.parse(rich.stdout).structuredContent).toEqual([1, 2, 3]); + expect(JSON.parse(rich.stdout).content.some((block: any) => block.type === 'audio')).toBe(true); + }); + it('returns a failing process status for tool-level failures', async () => { + const result = await run('call', 'stdio', 'fail', '--output-json'); + expect(result.code).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ isError: true }); + expect(result.stdout).not.toContain('successful'); + }); + it('returns exit 2 for required input and supports an explicit continuation', async () => { + const first = await run('call', 'stdio', 'confirm', '--output-json'); + expect(first.code).toBe(2); + const required = JSON.parse(first.stdout); + expect(required.resultType).toBe('input_required'); + const result = await run('call', 'stdio', 'confirm', '--output-json', '--request-state', required.requestState, '--input-responses', JSON.stringify({ approval: { action: 'accept', content: { approved: true } } })); + expect(result.code).toBe(0); + expect(JSON.parse(result.stdout).content[0].text).toBe('approved'); + }); + it('exposes resources, resource templates, prompts and completion from the CLI', async () => { + expect(JSON.parse((await run('resources', 'remote')).stdout).resources[0].uri).toBe('fixture://document'); + expect(JSON.parse((await run('resources', 'remote', '--templates')).stdout).resourceTemplates[0].uriTemplate).toBe('fixture://items/{name}'); + expect(JSON.parse((await run('read', 'remote', 'fixture://document')).stdout).contents[0].text).toBe('fixture document'); + expect(JSON.parse((await run('prompts', 'remote')).stdout).prompts[0].name).toBe('welcome'); + expect(JSON.parse((await run('prompt', 'remote', 'welcome', 'name=Taipei')).stdout).messages[0].content.text).toBe('Hello Taipei'); + const completion = await run('complete', 'remote', '--json', JSON.stringify({ ref: { type: 'ref/prompt', name: 'welcome' }, argument: { name: 'name', value: 'T' } })); + expect(JSON.parse(completion.stdout).completion.values).toEqual(['Taipei', 'Tokyo']); + }); + it('restarts a stdio connection and reaps its previous child', async () => { + const before = JSON.parse((await run('call', 'stdio', 'echo', 'text=before', '--output-json')).stdout).structuredContent.pid; + expect((await run('restart', 'stdio')).code).toBe(0); + const after = JSON.parse((await run('call', 'stdio', 'echo', 'text=after', '--output-json')).stdout).structuredContent.pid; + expect(after).not.toBe(before); + expect(() => process.kill(before, 0)).toThrow(); + }); + it('blocks disabled servers in both the CLI and direct daemon requests', async () => { + try { + expect((await run('update', 'stdio', '--disabled')).code).toBe(0); + expect((await run('tools', 'stdio', '--json')).code).toBe(1); + const result = await fetch('http://127.0.0.1:' + port + '/list', { method: 'POST', body: JSON.stringify({ server: 'stdio' }) }); + expect(result.status).toBe(500); + expect((await result.json()).error).toContain('disabled'); + } finally { await run('update', 'stdio', '--enabled'); } + }); + it('rejects invalid CLI timeouts, invalid ports and unknown tools', async () => { + expect((await run('call', 'stdio', 'echo', '--timeout', '-1')).code).toBe(1); + expect((await run('start', '--port', '0')).code).toBe(1); + expect((await run('call', 'stdio', 'missing', '--output-json')).code).toBe(1); + }); + it('validates daemon request bodies without accepting malformed JSON', async () => { + const result = await fetch('http://127.0.0.1:' + port + '/call', { method: 'POST', body: '{bad' }); + expect(result.status).toBe(400); + expect((await result.json()).error).toBe('Invalid request JSON'); + }); +}); diff --git a/src/tests/integration/helpers.ts b/src/tests/integration/helpers.ts new file mode 100644 index 0000000..bb6a169 --- /dev/null +++ b/src/tests/integration/helpers.ts @@ -0,0 +1,53 @@ +import { spawn, execFile, type ChildProcess } from 'node:child_process'; +import { promisify } from 'node:util'; +import fs from 'node:fs'; +import net from 'node:net'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export const repository = fileURLToPath(new URL('../../../', import.meta.url)); +export const fixture = path.join(repository, 'src/tests/fixtures/mcp-server.mjs'); +export async function runCli(args: string[], env: Record = {}) { + try { + const result = await promisify(execFile)(process.execPath, ['dist/index.js', ...args], { cwd: repository, env: { ...process.env, ...env }, timeout: 20000 }); + return { ...result, code: 0 }; + } catch (error: any) { + if (error.killed || typeof error.code !== 'number') throw error; + return { stdout: error.stdout as string, stderr: error.stderr as string, code: error.code as number }; + } +} +export async function startFixture(transport: 'http' | 'sse', env: Record = {}) { + const child = spawn(process.execPath, [fixture, transport], { cwd: repository, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] }); + let errors = ''; + child.stderr.on('data', chunk => { errors += chunk; }); + const port = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { child.kill(); reject(new Error('Fixture startup timed out: ' + errors)); }, 5000); + child.once('error', error => { clearTimeout(timer); reject(error); }); + child.once('exit', code => { clearTimeout(timer); reject(new Error('Fixture exited: ' + code + ' ' + errors)); }); + let output = ''; + child.stdout.on('data', chunk => { + output += chunk; + if (output.includes('\n')) { clearTimeout(timer); resolve(JSON.parse(output.trim()).port); } + }); + }); + return { child, port, url: 'http://127.0.0.1:' + port + (transport === 'sse' ? '/events' : '/mcp') }; +} +export async function stopFixture(child: ChildProcess) { + if (child.exitCode !== null) return; + await new Promise(resolve => { child.once('exit', () => resolve()); child.kill('SIGTERM'); }); +} +export async function freePort() { + const server = net.createServer(); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const port = (server.address() as net.AddressInfo).port; + await new Promise(resolve => server.close(() => resolve())); + return port; +} +export async function waitForDaemonExit(port: number) { + for (let attempt = 0; attempt < 40; attempt++) { + const running = await fetch('http://127.0.0.1:' + port + '/status', { signal: AbortSignal.timeout(500) }).then(() => true, () => false); + if (!running) return; + await new Promise(resolve => setTimeout(resolve, 100)); + } + throw new Error('Daemon did not exit'); +} diff --git a/src/tests/integration/protocol.test.ts b/src/tests/integration/protocol.test.ts new file mode 100644 index 0000000..298bc07 --- /dev/null +++ b/src/tests/integration/protocol.test.ts @@ -0,0 +1,132 @@ +import { beforeAll, afterAll, describe, it, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { McpClientService } from '../../core/client.js'; +import { fixture, startFixture, stopFixture } from './helpers.js'; + +describe('real MCP SDK interoperability', () => { + let directory: string; + let http: Awaited>; + let sse: Awaited>; + beforeAll(async () => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mcps-protocol-')); + http = await startFixture('http', { FIXTURE_REQUEST_LOG: path.join(directory, 'requests.jsonl') }); + sse = await startFixture('sse'); + }); + afterAll(async () => { + if (http) await stopFixture(http.child); + if (sse) await stopFixture(sse.child); + if (directory) fs.rmSync(directory, { recursive: true, force: true }); + }); + it('negotiates latest stdio, honors cwd/env, aggregates every tool page and closes the exact child', async () => { + const client = new McpClientService(); + try { + await client.connect({ command: process.execPath, args: [fixture], cwd: directory, env: { FIXTURE_EMPTY: '' } }, 'stdio'); + expect(client.getInfo()).toMatchObject({ protocolVersion: '2026-07-28', protocolEra: 'modern' }); + const { tools } = await client.listTools(); + expect(tools.map(tool => tool.name)).toEqual(['echo', 'rich', 'fail', 'confirm', 'add_tool']); + const result = await client.callTool('echo', { text: 'hello' }); + expect(result.structuredContent).toMatchObject({ text: 'hello', cwd: directory, empty: '' }); + await client.callTool('add_tool', {}); + expect((await client.listTools()).tools.some(tool => tool.name === 'added')).toBe(true); + } finally { await client.close(); } + await expect(client.listTools()).rejects.toThrow('Client not connected'); + }); + it('falls back to the actual v1 stdio server without losing interoperability', async () => { + const client = new McpClientService(); + try { + await client.connect({ command: process.execPath, args: [fixture, 'stdio', 'legacy'] }, 'legacy'); + expect(client.getInfo()).toMatchObject({ protocolVersion: '2025-11-25', protocolEra: 'legacy' }); + const result = await client.callTool('echo', { text: 'old server' }); + expect(result.content[0]).toMatchObject({ type: 'text', text: expect.stringContaining('old server') }); + expect((await client.callTool('confirm', {})).content[0]).toMatchObject({ type: 'text', text: 'cancel' }); + } finally { await client.close(); } + }); + it('rejects a modern-only pin against an old server', async () => { + const client = new McpClientService(); + try { + await expect(client.connect({ command: process.execPath, args: [fixture, 'stdio', 'legacy'], protocolVersion: '2026-07-28' })).rejects.toThrow(); + } finally { await client.close(); } + }); + it('uses stateless HTTP with per-request metadata and header authentication', async () => { + const client = new McpClientService(); + try { + await client.connect({ url: http.url, type: 'http', headers: { 'X-Fixture-Token': 'non-secret-test-token' } }); + await client.listTools(); + await client.callTool('echo', { text: 'modern HTTP' }); + expect(client.getInfo()).toMatchObject({ protocolVersion: '2026-07-28', protocolEra: 'modern' }); + const requests = fs.readFileSync(path.join(directory, 'requests.jsonl'), 'utf8').trim().split('\n').map(line => JSON.parse(line)); + expect(requests.some(request => request.method === 'server/discover')).toBe(true); + expect(requests.some(request => request.method === 'subscriptions/listen')).toBe(true); + expect(requests.some(request => request.method === 'initialize')).toBe(false); + for (const request of requests) { + expect(request.meta['io.modelcontextprotocol/protocolVersion']).toBe('2026-07-28'); + expect(request.meta['io.modelcontextprotocol/clientCapabilities'].elicitation).toEqual({ form: {}, url: {} }); + expect(request.protocolHeader).toBe('2026-07-28'); + expect(request.sessionHeader).toBeUndefined(); + expect(request.authorization).toBe('non-secret-test-token'); + } + } finally { await client.close(); } + }); + it('does not disguise an HTTP authorization error as a legacy server', async () => { + const client = new McpClientService(); + try { await expect(client.connect({ url: http.url.replace('/mcp', '/denied') })).rejects.toThrow(); } + finally { await client.close(); } + }); + it('preserves legacy SSE at an endpoint without /sse in its URL', async () => { + const client = new McpClientService(); + try { + await client.connect({ url: sse.url, type: 'sse' }, 'sse'); + expect(client.getInfo().protocolEra).toBe('legacy'); + expect((await client.listTools()).tools[0].name).toBe('echo'); + } finally { await client.close(); } + }); + it('preserves arbitrary structured output, audio, resource links and metadata', async () => { + const client = new McpClientService(); + try { + await client.connect({ url: http.url }); + await client.listTools(); + const result = await client.callTool('rich', {}); + expect(result.structuredContent).toEqual([1, 2, 3]); + expect(result._meta?.['org.example/fixture']).toBe(true); + expect(result.content).toEqual(expect.arrayContaining([expect.objectContaining({ type: 'audio' }), expect.objectContaining({ type: 'resource_link' })])); + } finally { await client.close(); } + }); + it('reads resources/templates, gets prompts and requests completion', async () => { + const client = new McpClientService(); + try { + await client.connect({ url: http.url }); + expect(await client.request('resources/list')).toMatchObject({ resources: [expect.objectContaining({ uri: 'fixture://document' })] }); + expect(await client.request('resources/templates/list')).toMatchObject({ resourceTemplates: [expect.objectContaining({ uriTemplate: 'fixture://items/{name}' })] }); + expect(await client.request('resources/read', { uri: 'fixture://document' })).toMatchObject({ contents: [expect.objectContaining({ text: 'fixture document' })] }); + expect(await client.request('prompts/list')).toMatchObject({ prompts: [expect.objectContaining({ name: 'welcome' })] }); + expect(await client.request('prompts/get', { name: 'welcome', arguments: { name: 'Taipei' } })).toMatchObject({ messages: [expect.objectContaining({ content: { type: 'text', text: 'Hello Taipei' } })] }); + expect(await client.request('completion/complete', { ref: { type: 'ref/prompt', name: 'welcome' }, argument: { name: 'name', value: 'T' } })).toMatchObject({ completion: { values: ['Taipei', 'Tokyo'] } }); + } finally { await client.close(); } + }); + it('surfaces input-required results and retries with exact opaque request state', async () => { + const client = new McpClientService(); + try { + await client.connect({ url: http.url }); + const first: any = await client.callTool('confirm', {}); + expect(first).toMatchObject({ resultType: 'input_required', requestState: 'approval-step', inputRequests: { approval: expect.any(Object) } }); + const result = await client.callTool('confirm', {}, 3000, { requestState: first.requestState, inputResponses: { approval: { action: 'accept', content: { approved: true } } } }); + expect(result.content).toEqual([{ type: 'text', text: 'approved' }]); + } finally { await client.close(); } + }); + it('discovers OAuth metadata and authenticates using issuer-bound client credentials', async () => { + const client = new McpClientService(); + const previous = process.env.MCPS_FIXTURE_SECRET; + process.env.MCPS_FIXTURE_SECRET = 'fixture-secret'; + try { + await client.connect({ url: http.url.replace('/mcp', '/oauth/mcp'), auth: { type: 'client_credentials', clientId: 'fixture-client', clientSecretEnv: 'MCPS_FIXTURE_SECRET', issuer: http.url.replace('/mcp', '/issuer'), scope: 'mcp:read' } }); + expect(client.getInfo().protocolVersion).toBe('2026-07-28'); + expect((await client.listTools()).tools).toHaveLength(5); + } finally { + await client.close(); + if (previous === undefined) delete process.env.MCPS_FIXTURE_SECRET; + else process.env.MCPS_FIXTURE_SECRET = previous; + } + }); +}); diff --git a/src/tests/unit/call-logging.test.ts b/src/tests/unit/call-logging.test.ts index cffdda4..f89f3dc 100644 --- a/src/tests/unit/call-logging.test.ts +++ b/src/tests/unit/call-logging.test.ts @@ -1,73 +1,51 @@ -import { describe, it, expect } from 'vitest'; - -describe('tool call logging format', () => { - describe('log message formatting', () => { - it('should format tool request message correctly', () => { - const serverName = 'test-server'; - const toolName = 'test_tool'; - const args = { arg1: 'value1', arg2: 123 }; - - const message = `[Tool Request] Server: ${serverName}, Tool: ${toolName}, Args: ${JSON.stringify(args)}`; - - expect(message).toContain('[Tool Request]'); - expect(message).toContain(`Server: ${serverName}`); - expect(message).toContain(`Tool: ${toolName}`); - expect(message).toContain('Args:'); - expect(message).toContain('arg1'); - expect(message).toContain('value1'); - }); - - it('should format tool response message correctly', () => { - const serverName = 'test-server'; - const toolName = 'test_tool'; - const result = { content: [{ type: 'text', text: 'success' }] }; - - const message = `[Tool Response] Server: ${serverName}, Tool: ${toolName}, Result: ${JSON.stringify(result)}`; - - expect(message).toContain('[Tool Response]'); - expect(message).toContain(`Server: ${serverName}`); - expect(message).toContain(`Tool: ${toolName}`); - expect(message).toContain('Result:'); - }); - - it('should handle empty args', () => { - const serverName = 'test-server'; - const toolName = 'test_tool'; - const args = {}; - - const message = `[Tool Request] Server: ${serverName}, Tool: ${toolName}, Args: ${JSON.stringify(args)}`; - - expect(message).toContain('Args: {}'); - }); - - it('should handle complex nested args', () => { - const serverName = 'test-server'; - const toolName = 'test_tool'; - const args = { - user: { name: 'Alice', settings: { theme: 'dark' } }, - items: [1, 2, 3] - }; - - const message = `[Tool Request] Server: ${serverName}, Tool: ${toolName}, Args: ${JSON.stringify(args)}`; - - expect(message).toContain('Alice'); - expect(message).toContain('dark'); - expect(message).toContain('items'); - }); - - it('should log by default without MCPS_VERBOSE environment variable', () => { - // 确保 MCPS_VERBOSE 未设置时也默认记录日志 - delete process.env.MCPS_VERBOSE; - - // 日志记录不依赖 MCPS_VERBOSE 环境变量 - const serverName = 'test-server'; - const toolName = 'test_tool'; - const args = { test: 'value' }; - - // 无论 MCPS_VERBOSE 是否设置,都应该记录日志 - const message = `[Tool Request] Server: ${serverName}, Tool: ${toolName}, Args: ${JSON.stringify(args)}`; - - expect(message).toBeDefined(); - }); +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { Client } from '@modelcontextprotocol/client'; +import { McpClientService } from '../../core/client.js'; +import { printResult } from '../../commands/call.js'; + +describe('actual tool calls, logging and result rendering', () => { + let service: McpClientService; + beforeEach(async () => { + vi.spyOn(Client.prototype, 'connect').mockResolvedValue(); + vi.spyOn(Client.prototype, 'close').mockResolvedValue(); + vi.spyOn(Client.prototype, 'callTool').mockResolvedValue({ content: [{ type: 'text', text: 'result' }] }); + vi.spyOn(console, 'log').mockImplementation(() => {}); + service = new McpClientService(); + await service.connect({ url: 'https://example.org/mcp' }, 'server'); + }); + afterEach(async () => { await service.close(); vi.unstubAllEnvs(); vi.restoreAllMocks(); }); + it('passes the tool, arguments, timeout and continuation to the SDK', async () => { + await service.callTool('echo', { text: 'hello' }, 1200, { requestState: 'opaque' }); + expect(Client.prototype.callTool).toHaveBeenCalledWith( + { name: 'echo', arguments: { text: 'hello' }, requestState: 'opaque' }, + { timeout: 1200, maxTotalTimeout: 1200, allowInputRequired: true }, + ); + }); + it('logs actual requests only in verbose mode without logging sensitive arguments or results', async () => { + vi.stubEnv('MCPS_VERBOSE', 'true'); + await service.callTool('echo', { token: 'private-test-value' }); + const output = vi.mocked(console.log).mock.calls.flat().join('\n'); + expect(output).toContain('[Tool Request] Server: server, Tool: echo'); + expect(output).toContain('[Tool Response] Server: server, Tool: echo'); + expect(output).not.toContain('private-test-value'); + expect(output).not.toContain('result'); + }); + it('keeps normal tool calls quiet', async () => { + vi.stubEnv('MCPS_VERBOSE', 'false'); + await service.callTool('echo', {}); + expect(console.log).not.toHaveBeenCalled(); + }); + it('renders audio, resource links, embedded text and non-object structured content', () => { + printResult({ content: [ + { type: 'audio', mimeType: 'audio/wav', data: 'abc' }, + { type: 'resource_link', uri: 'test://resource' }, + { type: 'resource', resource: { uri: 'test://embedded', text: 'embedded text' } }, + ], structuredContent: [1, 2] }); + expect(vi.mocked(console.log).mock.calls.flat()).toEqual(['[Audio: audio/wav]', '[Resource: test://resource]', 'embedded text', '[\n 1,\n 2\n]']); + }); + it('preserves input-required state in rendering', () => { + const result = { resultType: 'input_required', requestState: 'opaque', inputRequests: {} }; + printResult(result); + expect(JSON.parse(vi.mocked(console.log).mock.calls[0][0])).toEqual(result); }); }); diff --git a/src/tests/unit/client-headers.test.ts b/src/tests/unit/client-headers.test.ts index b6f470b..a7158c1 100644 --- a/src/tests/unit/client-headers.test.ts +++ b/src/tests/unit/client-headers.test.ts @@ -1,67 +1,35 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; - -// Mock the MCP SDK transports before importing client const mockStreamableHTTPConnect = vi.fn().mockResolvedValue(undefined); const mockSSEConnect = vi.fn().mockResolvedValue(undefined); - let capturedStreamableHTTPUrl: URL | undefined; let capturedStreamableHTTPOpts: any; let capturedSSEUrl: URL | undefined; let capturedSSEOpts: any; - -vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({ +vi.mock('@modelcontextprotocol/client', () => ({ StreamableHTTPClientTransport: class { - constructor(url: URL, opts?: any) { - capturedStreamableHTTPUrl = url; - capturedStreamableHTTPOpts = opts; - } + constructor(url: URL, opts?: any) { capturedStreamableHTTPUrl = url; capturedStreamableHTTPOpts = opts; } start = mockStreamableHTTPConnect; close = vi.fn(); - set onclose(_: any) {} - set onerror(_: any) {} - set onmessage(_: any) {} - } -})); - -vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({ + }, SSEClientTransport: class { - constructor(url: URL, opts?: any) { - capturedSSEUrl = url; - capturedSSEOpts = opts; - } + constructor(url: URL, opts?: any) { capturedSSEUrl = url; capturedSSEOpts = opts; } start = mockSSEConnect; close = vi.fn(); - set onclose(_: any) {} - set onerror(_: any) {} - set onmessage(_: any) {} - } -})); - -vi.mock('@modelcontextprotocol/sdk/client/stdio.js', () => ({ - StdioClientTransport: class { - constructor(_opts: any) {} - start = vi.fn().mockResolvedValue(undefined); - close = vi.fn(); - set onclose(_: any) {} - set onerror(_: any) {} - set onmessage(_: any) {} - } -})); - -vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({ + }, Client: class { - constructor(_info: any, _opts: any) {} connect = vi.fn().mockResolvedValue(undefined); listTools = vi.fn().mockResolvedValue({ tools: [] }); callTool = vi.fn().mockResolvedValue({ result: 'ok' }); - close = vi.fn(); - } + close = vi.fn().mockResolvedValue(undefined); + setRequestHandler = vi.fn(); + }, })); - -vi.mock('eventsource', () => ({ - EventSource: class {} +vi.mock('@modelcontextprotocol/client/stdio', () => ({ + StdioClientTransport: class { + start = vi.fn().mockResolvedValue(undefined); + close = vi.fn().mockResolvedValue(undefined); + } })); - import { McpClientService } from '../../core/client.js'; import { detectServerType, HttpServerConfigSchema } from '../../types/config.js'; diff --git a/src/tests/unit/config-safety.test.ts b/src/tests/unit/config-safety.test.ts new file mode 100644 index 0000000..73f0240 --- /dev/null +++ b/src/tests/unit/config-safety.test.ts @@ -0,0 +1,96 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { ConfigManager } from '../../core/config.js'; + +describe('configuration safety', () => { + let directory: string; + let file: string; + let manager: ConfigManager; + beforeEach(() => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'mcps-config-safety-')); + file = path.join(directory, 'mcp.json'); + manager = new ConfigManager(directory); + vi.stubEnv('MCPS_DAEMON_TIMEOUT', ''); + }); + afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); + const write = (value: unknown) => fs.writeFileSync(file, JSON.stringify(value)); + const read = () => JSON.parse(fs.readFileSync(file, 'utf8')); + + it('reads root timeout and preserves root/extension fields across writes', () => { + write({ mcpServers: { original: { command: 'node', custom: { enabled: true } } }, daemonTimeout: 90000, customRoot: { revision: 3 } }); + expect(manager.getDaemonTimeout()).toBe(90000); + manager.addServer('new', { command: 'node' }); + manager.renameServer('new', 'renamed'); + manager.updateServer('renamed', { args: ['--version'] }); + manager.removeServer('renamed'); + expect(read()).toEqual({ mcpServers: { original: { command: 'node', custom: { enabled: true } } }, daemonTimeout: 90000, customRoot: { revision: 3 } }); + }); + it.each(['broken JSON', '', '{'])('refuses to overwrite unreadable JSON: %j', content => { + fs.writeFileSync(file, content); + expect(() => manager.addServer('new', { command: 'node' })).toThrow('Original file was not changed'); + expect(fs.readFileSync(file, 'utf8')).toBe(content); + expect(fs.readdirSync(directory)).toEqual(['mcp.json']); + }); + it.each([{ value: null }, { value: [] }, { value: { servers: [] } }, { value: { mcpServers: [] } }])('refuses to overwrite an unsupported root: %j', ({ value }) => { + write(value); + const original = fs.readFileSync(file, 'utf8'); + expect(() => manager.addServer('new', { command: 'node' })).toThrow('Original file was not changed'); + expect(fs.readFileSync(file, 'utf8')).toBe(original); + }); + it('preserves invalid existing entries rather than deleting them during a write', () => { + write({ mcpServers: { bad: { url: 'bad URL' }, good: { command: 'node' } } }); + const original = fs.readFileSync(file, 'utf8'); + expect(manager.listServers().map(server => server.name)).toEqual(['good']); + expect(() => manager.updateServer('good', { args: [] })).toThrow('Original file was not changed'); + expect(fs.readFileSync(file, 'utf8')).toBe(original); + expect(() => manager.validateConfig()).toThrow('bad'); + }); + it.each([{ url: 'not-a-url' }, { command: '' }, { command: 'node', url: 'https://example.org/mcp' }, { url: 'ftp://example.org/file' }])('validates additions before persisting: %j', server => { + expect(() => manager.addServer('bad', server as any)).toThrow(); + expect(fs.existsSync(file)).toBe(false); + }); + it('makes environment timeout override explicit and rejects malformed overrides', () => { + write({ mcpServers: {}, daemonTimeout: 90000 }); + vi.stubEnv('MCPS_DAEMON_TIMEOUT', '12'); + expect(manager.getDaemonTimeout()).toBe(12000); + vi.stubEnv('MCPS_DAEMON_TIMEOUT', '12bad'); + expect(manager.getDaemonTimeout()).toBe(90000); + vi.stubEnv('MCPS_DAEMON_TIMEOUT', '-1'); + expect(manager.getDaemonTimeout()).toBe(90000); + }); + it('leaves the original file intact when atomic replacement fails', () => { + write({ mcpServers: { original: { command: 'node' } } }); + const original = fs.readFileSync(file, 'utf8'); + vi.spyOn(fs, 'renameSync').mockImplementation(() => { throw new Error('simulated disk error'); }); + expect(() => manager.addServer('new', { command: 'node' })).toThrow('simulated disk error'); + expect(fs.readFileSync(file, 'utf8')).toBe(original); + expect(fs.readdirSync(directory)).toEqual(['mcp.json']); + }); + it('refuses an overlapping writer and preserves its lock', () => { + fs.writeFileSync(file + '.lock', 'another writer'); + expect(() => manager.addServer('new', { command: 'node' })).toThrow('being updated'); + expect(fs.readFileSync(file + '.lock', 'utf8')).toBe('another writer'); + }); + it('switches transports without retaining conflicting old fields', () => { + manager.addServer('server', { command: 'node', args: ['old.js'], cwd: '/tmp' }); + manager.updateServer('server', { url: 'https://example.org/events', type: 'sse' }); + expect(manager.getServer('server')).toMatchObject({ url: 'https://example.org/events', type: 'sse' }); + expect(manager.getServer('server')).not.toHaveProperty('command'); + manager.updateServer('server', { command: 'python' }); + expect(manager.getServer('server')).toMatchObject({ command: 'python', type: 'stdio' }); + expect(manager.getServer('server')).not.toHaveProperty('url'); + }); + it('does not overwrite a valid configuration on an invalid update', () => { + manager.addServer('server', { command: 'node' }); + const original = fs.readFileSync(file, 'utf8'); + expect(() => manager.updateServer('server', { url: 'broken' })).toThrow('Invalid update'); + expect(fs.readFileSync(file, 'utf8')).toBe(original); + }); + it('handles names inherited from Object.prototype as ordinary server names', () => { + manager.addServer('constructor', { command: 'node' }); + expect(manager.getServer('constructor')?.command).toBe('node'); + expect(manager.getServer('toString')).toBeUndefined(); + }); +}); diff --git a/src/tests/unit/daemon-router.test.ts b/src/tests/unit/daemon-router.test.ts new file mode 100644 index 0000000..32390ea --- /dev/null +++ b/src/tests/unit/daemon-router.test.ts @@ -0,0 +1,97 @@ +import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest'; +import { once } from 'node:events'; +import type { AddressInfo } from 'node:net'; +import type { Server } from 'node:http'; +import { Command } from 'commander'; +const mocks = vi.hoisted(() => ({ + client: { listTools: vi.fn(), callTool: vi.fn(), request: vi.fn() }, + pool: { initializeAll: vi.fn(), getInitStatus: vi.fn(), getActiveConnectionDetails: vi.fn(), getClient: vi.fn(), closeClient: vi.fn(), closeAll: vi.fn() }, +})); +vi.mock('../../core/pool.js', () => ({ connectionPool: mocks.pool })); +vi.mock('../../core/config.js', () => ({ configManager: { getConfigPath: () => '/test-fixture/mcp.json', validateConfig: vi.fn(), getDaemonTimeout: () => 1000 } })); +import { startDaemon, registerDaemonCommand } from '../../commands/daemon.js'; +import { daemonRequest } from '../../core/daemon-client.js'; + +describe('daemon HTTP routing and command errors', () => { + let server: Server; + let port: number; + let previousExitCode: typeof process.exitCode; + beforeEach(async () => { + previousExitCode = process.exitCode; process.exitCode = 0; + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(console, 'table').mockImplementation(() => {}); + mocks.pool.initializeAll.mockResolvedValue(undefined); + mocks.pool.getInitStatus.mockReturnValue({ initializing: false, initialized: true }); + mocks.pool.getActiveConnectionDetails.mockResolvedValue([{ name: 'server', status: 'connected', toolsCount: 1, protocolVersion: '2026-07-28' }]); + mocks.pool.getClient.mockResolvedValue(mocks.client); + mocks.pool.closeClient.mockResolvedValue(true); + mocks.pool.closeAll.mockResolvedValue(undefined); + mocks.client.listTools.mockResolvedValue({ tools: [{ name: 'echo' }] }); + mocks.client.callTool.mockResolvedValue({ content: [{ type: 'text', text: 'hello' }] }); + mocks.client.request.mockResolvedValue({ resources: [] }); + server = startDaemon(0); + await once(server, 'listening'); + port = (server.address() as AddressInfo).port; + }); + afterEach(async () => { + await new Promise(resolve => { server.close(() => resolve()); server.closeAllConnections(); }); + process.exitCode = previousExitCode; + vi.restoreAllMocks(); vi.clearAllMocks(); + }); + const post = (endpoint: string, body: unknown) => daemonRequest('POST', endpoint, body, port, 1000); + const command = async (...args: string[]) => { + const program = new Command().exitOverride(); + registerDaemonCommand(program); + await program.parseAsync(['node', 'mcps', ...args]); + }; + it('returns current configuration, readiness and protocol metadata', async () => { + const status = await daemonRequest('GET', '/status', undefined, port); + expect(status).toMatchObject({ status: 'running', initialized: true, configPath: '/test-fixture/mcp.json' }); + expect(status.connections[0].protocolVersion).toBe('2026-07-28'); + }); + it('forwards tool arguments, timeout and opaque continuation fields', async () => { + expect(await post('/call', { server: 'server', tool: 'echo', args: { text: 'hello' }, timeout: 10, inputResponses: {}, requestState: 'opaque' })).toEqual({ result: { content: [{ type: 'text', text: 'hello' }] } }); + expect(mocks.client.callTool).toHaveBeenCalledWith('echo', { text: 'hello' }, 10, { inputResponses: {}, requestState: 'opaque' }); + }); + it('uses fresh SDK tools rather than a separate stale pool cache', async () => { + expect(await post('/list', { server: 'server' })).toEqual({ tools: [{ name: 'echo' }] }); + mocks.client.listTools.mockResolvedValue({ tools: [{ name: 'added' }] }); + expect(await post('/list', { server: 'server' })).toEqual({ tools: [{ name: 'added' }] }); + }); + it('forwards resource and prompt operations through the shared connection', async () => { + expect(await post('/protocol', { server: 'server', operation: 'resources/list', params: {}, timeout: 300 })).toEqual({ result: { resources: [] } }); + expect(mocks.client.request).toHaveBeenCalledWith('resources/list', {}, 300); + }); + it.each([{ body: null }, { body: [] }, { body: { tool: 'echo' } }, { body: { server: 'server' } }])('rejects an invalid call body: %j', async ({ body }) => { + await expect(post('/call', body)).rejects.toThrow(); + expect(mocks.client.callTool).not.toHaveBeenCalled(); + }); + it('preserves typed protocol errors through daemon responses', async () => { + mocks.client.callTool.mockRejectedValue(Object.assign(new Error('unsupported protocol'), { code: -32022, data: { supportedVersions: ['2026-07-28'] } })); + await expect(post('/call', { server: 'server', tool: 'echo' })).rejects.toMatchObject({ message: 'unsupported protocol', code: -32022, data: { supportedVersions: ['2026-07-28'] } }); + }); + it('restarts an individual client or the entire pool', async () => { + await post('/restart', { server: 'server' }); + expect(mocks.pool.closeClient).toHaveBeenCalledWith('server'); + await post('/restart', {}); + expect(mocks.pool.closeAll).toHaveBeenCalled(); + expect(mocks.pool.initializeAll).toHaveBeenCalledTimes(2); + }); + it('returns JSON from the actual status command and recognizes an already running daemon', async () => { + await command('status', '--port', String(port), '--json'); + expect(JSON.parse(vi.mocked(console.log).mock.calls[0][0]).status).toBe('running'); + await command('start', '--port', String(port)); + expect(console.log).toHaveBeenCalledWith(expect.stringContaining('already running')); + }); + it('exercises legacy aliases and returns failure for an invalid port', async () => { + await command('daemon', 'status', '--port', String(port)); + expect(console.table).toHaveBeenCalled(); + await command('start', '--port', 'invalid'); + expect(process.exitCode).toBe(1); + }); + it('reports unknown routes as errors', async () => { + await expect(daemonRequest('GET', '/missing', undefined, port)).rejects.toThrow('Unknown daemon endpoint'); + await expect(post('/missing', {})).rejects.toThrow('Unknown daemon endpoint'); + }); +}); diff --git a/src/tests/unit/pool.test.ts b/src/tests/unit/pool.test.ts new file mode 100644 index 0000000..1641a8e --- /dev/null +++ b/src/tests/unit/pool.test.ts @@ -0,0 +1,71 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +const state = vi.hoisted(() => ({ instances: [] as any[], connect: vi.fn() })); +vi.mock('../../core/client.js', () => ({ + McpClientService: class { + connect = state.connect; + close = vi.fn().mockResolvedValue(undefined); + listTools = vi.fn().mockResolvedValue({ tools: [{ name: 'one' }] }); + getInfo = vi.fn().mockReturnValue({ protocolVersion: '2026-07-28' }); + constructor() { state.instances.push(this); } + }, +})); +vi.mock('../../core/config.js', () => ({ configManager: { getServer: vi.fn(), listServers: vi.fn() } })); +import { configManager } from '../../core/config.js'; +import { ConnectionPool } from '../../core/pool.js'; + +describe('connection ownership, failures and races', () => { + let pool: ConnectionPool; + beforeEach(() => { + pool = new ConnectionPool(); + state.instances.length = 0; + state.connect.mockReset().mockResolvedValue(undefined); + vi.mocked(configManager.getServer).mockReturnValue({ name: 'server', command: 'node' }); + vi.mocked(configManager.listServers).mockReturnValue([{ name: 'server', command: 'node' }]); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(process.stdout, 'write').mockImplementation(() => true); + }); + afterEach(async () => { await pool.closeAll(); vi.restoreAllMocks(); vi.unstubAllEnvs(); }); + it('deduplicates concurrent requests and clears the connection timeout', async () => { + await Promise.all([pool.getClient('server', { timeoutMs: 1000 }), pool.getClient('server', { timeoutMs: 1000 })]); + expect(state.instances).toHaveLength(1); + expect(state.connect).toHaveBeenCalledTimes(1); + expect(await pool.getActiveConnectionDetails()).toEqual([expect.objectContaining({ name: 'server', toolsCount: 1, protocolVersion: '2026-07-28' })]); + }); + it('closes a timed-out connection and reports its failure', async () => { + state.connect.mockImplementation(() => new Promise(() => {})); + await expect(pool.getClient('server', { timeoutMs: 10 })).rejects.toThrow('Connection timeout'); + expect(state.instances[0].close).toHaveBeenCalled(); + expect(await pool.getActiveConnectionDetails()).toEqual([expect.objectContaining({ name: 'server', status: 'error' })]); + }); + it('cannot resurrect a connection after a pool reset', async () => { + let finish!: () => void; + state.connect.mockImplementation(() => new Promise(resolve => { finish = resolve; })); + const pending = pool.getClient('server'); + await pool.closeAll(); + finish(); + await expect(pending).rejects.toThrow('reset'); + expect(await pool.getActiveConnectionDetails()).toEqual([]); + }); + it('blocks disabled and missing servers before spawning anything', async () => { + vi.mocked(configManager.getServer).mockReturnValue({ name: 'server', command: 'node', disabled: true }); + await expect(pool.getClient('server')).rejects.toThrow('disabled'); + vi.mocked(configManager.getServer).mockReturnValue(undefined); + await expect(pool.getClient('missing')).rejects.toThrow('not found'); + expect(state.instances).toEqual([]); + }); + it('initializes only enabled servers and exposes diagnostic failures', async () => { + vi.mocked(configManager.listServers).mockReturnValue([{ name: 'server', command: 'node' }, { name: 'disabled', command: 'node', disabled: true }]); + state.connect.mockRejectedValue(new Error('connection unavailable')); + await pool.initializeAll(); + expect(state.connect).toHaveBeenCalledTimes(1); + expect(pool.getInitStatus()).toEqual({ initializing: false, initialized: true }); + expect(await pool.getActiveConnectionDetails()).toEqual([expect.objectContaining({ name: 'server', error: 'connection unavailable' })]); + }); + it('closes and recreates a selected client without reusing stale state', async () => { + const original = await pool.getClient('server'); + expect(await pool.closeClient('server')).toBe(true); + const next = await pool.getClient('server'); + expect(next).not.toBe(original); + expect(await pool.closeClient('missing')).toBe(false); + }); +}); diff --git a/src/tests/unit/protocol-cli.test.ts b/src/tests/unit/protocol-cli.test.ts new file mode 100644 index 0000000..225831e --- /dev/null +++ b/src/tests/unit/protocol-cli.test.ts @@ -0,0 +1,67 @@ +import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest'; +import { Command } from 'commander'; +vi.mock('../../core/config.js', () => ({ configManager: { getServer: vi.fn() } })); +vi.mock('../../core/daemon-client.js', () => ({ DaemonClient: { ensureDaemon: vi.fn(), request: vi.fn() } })); +import { configManager } from '../../core/config.js'; +import { DaemonClient } from '../../core/daemon-client.js'; +import { registerProtocolCommands } from '../../commands/protocol.js'; +describe('MCP protocol command parameters and failures', () => { + let previousExitCode: typeof process.exitCode; + beforeEach(() => { + previousExitCode = process.exitCode; process.exitCode = 0; + vi.mocked(configManager.getServer).mockReturnValue({ name: 'server', command: 'node' }); + vi.mocked(DaemonClient.request).mockResolvedValue({ resources: [] }); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + }); + afterEach(() => { process.exitCode = previousExitCode; vi.restoreAllMocks(); vi.clearAllMocks(); }); + const run = async (...args: string[]) => { + const program = new Command().exitOverride(); + registerProtocolCommands(program); + await program.parseAsync(['node', 'mcps', ...args]); + }; + it.each([ + ['discover', 'info'], ['resources', 'resources/list'], ['prompts', 'prompts/list'], + ])('routes %s to %s', async (command, operation) => { + await run(command, 'server'); + expect(DaemonClient.request).toHaveBeenCalledWith('server', operation, {}); + expect(JSON.parse(vi.mocked(console.log).mock.calls[0][0])).toEqual({ resources: [] }); + }); + it('preserves resource request state and manual input responses', async () => { + await run('read', 'server', 'test://document', '--request-state', 'opaque', '--input-responses', '{"approval":{"action":"decline"}}'); + expect(DaemonClient.request).toHaveBeenCalledWith('server', 'resources/read', { uri: 'test://document', requestState: 'opaque', inputResponses: { approval: { action: 'decline' } } }); + }); + it('selects templates and preserves string prompt arguments', async () => { + await run('resources', 'server', '--templates'); + expect(DaemonClient.request).toHaveBeenCalledWith('server', 'resources/templates/list', {}); + await run('prompt', 'server', 'welcome', 'code=001', 'enabled=true'); + expect(DaemonClient.request).toHaveBeenCalledWith('server', 'prompts/get', { name: 'welcome', arguments: { code: '001', enabled: 'true' } }); + }); + it('accepts JSON prompt and completion parameters', async () => { + await run('prompt', 'server', 'welcome', '--json', '{"name":"Taipei"}'); + expect(DaemonClient.request).toHaveBeenCalledWith('server', 'prompts/get', { name: 'welcome', arguments: { name: 'Taipei' } }); + await run('complete', 'server', '--json', '{"ref":{"type":"ref/prompt","name":"welcome"},"argument":{"name":"name","value":"T"}}'); + expect(DaemonClient.request).toHaveBeenCalledWith('server', 'completion/complete', expect.objectContaining({ argument: { name: 'name', value: 'T' } })); + }); + it.each(['[]', '{"name":1}', '{invalid'])('rejects invalid prompt parameters: %s', async json => { + await run('prompt', 'server', 'welcome', '--json', json); + expect(process.exitCode).toBe(1); + expect(DaemonClient.ensureDaemon).not.toHaveBeenCalled(); + }); + it('does not connect an unknown or disabled server', async () => { + vi.mocked(configManager.getServer).mockReturnValue(undefined); + await run('discover', 'missing'); + expect(process.exitCode).toBe(1); + vi.mocked(configManager.getServer).mockReturnValue({ name: 'server', command: 'node', disabled: true }); + await run('resources', 'server'); + expect(DaemonClient.ensureDaemon).not.toHaveBeenCalled(); + }); + it('returns exit 2 for incomplete requests and exit 1 for transport failures', async () => { + vi.mocked(DaemonClient.request).mockResolvedValue({ resultType: 'input_required', requestState: 'opaque' }); + await run('read', 'server', 'test://document'); + expect(process.exitCode).toBe(2); + vi.mocked(DaemonClient.request).mockRejectedValue(new Error('transport failed')); + await run('resources', 'server'); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/src/tests/unit/server-cli.test.ts b/src/tests/unit/server-cli.test.ts new file mode 100644 index 0000000..e951e2e --- /dev/null +++ b/src/tests/unit/server-cli.test.ts @@ -0,0 +1,102 @@ +import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { Command } from 'commander'; + +vi.mock('../../core/config.js', async importOriginal => { + const actual = await importOriginal(); + const fs = await import('node:fs'); + const os = await import('node:os'); + const path = await import('node:path'); + return { ...actual, configManager: new actual.ConfigManager(fs.mkdtempSync(path.join(os.tmpdir(), 'mcps-cli-config-'))) }; +}); +import { configManager } from '../../core/config.js'; +import { registerServerCommands } from '../../commands/server.js'; +import { detectServerType } from '../../types/config.js'; + +describe('real CLI configuration handlers', () => { + const file = configManager.getConfigPath(); + const directory = path.dirname(file); + let previousExitCode: typeof process.exitCode; + beforeEach(() => { + previousExitCode = process.exitCode; + process.exitCode = 0; + fs.rmSync(directory, { recursive: true, force: true }); + fs.mkdirSync(directory); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + }); + afterEach(() => { process.exitCode = previousExitCode; vi.restoreAllMocks(); fs.rmSync(directory, { recursive: true, force: true }); }); + const run = async (args: string[]) => { + const program = new Command().exitOverride(); + registerServerCommands(program); + await program.parseAsync(['node', 'mcps', ...args]); + }; + it('adds, renames, updates and removes using parsed CLI arguments', async () => { + await run(['add', 'server', '--command', 'node', '--args', 'server.js', '--env', 'EMPTY=', 'WITH_EQUALS=a=b', '--cwd', '/tmp']); + expect(configManager.getServer('server')).toMatchObject({ args: ['server.js'], env: { EMPTY: '', WITH_EQUALS: 'a=b' }, cwd: '/tmp' }); + await run(['rename', 'server', 'renamed']); + await run(['update', 'renamed', '--env', 'NEW=value', '--disabled']); + expect(configManager.getServer('renamed')).toMatchObject({ disabled: true, env: { EMPTY: '', NEW: 'value' } }); + await run(['update', 'renamed', '--enabled']); + expect(configManager.getServer('renamed')?.disabled).toBe(false); + await run(['ls']); + expect(console.log).toHaveBeenCalledWith(expect.stringContaining('renamed')); + await run(['rm', 'renamed']); + expect(configManager.listServers()).toEqual([]); + }); + it.each(['sse', 'http', 'streamableHttp'])('preserves explicit remote transport %s instead of guessing from URL', async type => { + await run(['add', 'remote', '--type', type, '--url', 'https://example.org/events', '--header', 'X-Token=${TOKEN}', '--protocol-version', 'legacy']); + expect(configManager.getServer('remote')).toMatchObject({ type, headers: { 'X-Token': '${TOKEN}' }, protocolVersion: 'legacy' }); + expect(detectServerType(configManager.getServer('remote')!)).toBe(type === 'sse' ? 'sse' : 'http'); + }); + it.each([ + ['add', 'bad', '--type', 'http', '--url', 'broken'], + ['add', 'bad', '--type', 'unknown', '--command', 'node'], + ['add', 'bad', '--command', 'node', '--env', 'BAD'], + ['add', 'bad'], + ['rm', 'missing'], + ['rename', 'missing', 'other'], + ['update', 'missing', '--command', 'node'], + ])('returns a failure exit code for %j', async (...args) => { + await run(args); + expect(process.exitCode).toBe(1); + expect(console.error).toHaveBeenCalled(); + expect(configManager.listServers()).toEqual([]); + }); + it('does not overwrite broken JSON through the actual add command', async () => { + fs.writeFileSync(file, '{broken fixture'); + await run(['add', 'new', '--command', 'node']); + expect(process.exitCode).toBe(1); + expect(fs.readFileSync(file, 'utf8')).toBe('{broken fixture'); + }); + it('reports the actual config path and rejects invalid configurations', async () => { + await run(['config', 'path']); + expect(console.log).toHaveBeenCalledWith(file); + fs.writeFileSync(file, JSON.stringify({ servers: [] })); + await run(['config', 'validate']); + expect(process.exitCode).toBe(1); + }); + it('keeps legacy command aliases working', async () => { + await run(['server', 'add', 'legacy', '--command', 'node']); + await run(['server', 'update', 'legacy', '--args', 'hello.js']); + await run(['server', 'rename', 'legacy', 'renamed']); + await run(['server', 'list']); + expect(configManager.getServer('renamed')?.args).toEqual(['hello.js']); + await run(['server', 'remove', 'renamed']); + expect(configManager.listServers()).toEqual([]); + }); + it('saves OAuth metadata with only the secret variable name and pins the issuer', async () => { + await run(['add', 'oauth', '--type', 'http', '--url', 'https://example.org/mcp', '--oauth-client-id', 'client', '--oauth-client-secret-env', 'MCP_CLIENT_SECRET', '--oauth-issuer', 'https://auth.example.org', '--oauth-scope', 'mcp:read']); + expect(configManager.getServer('oauth')?.auth).toEqual({ type: 'client_credentials', clientId: 'client', clientSecretEnv: 'MCP_CLIENT_SECRET', issuer: 'https://auth.example.org', scope: 'mcp:read' }); + await run(['update', 'oauth', '--oauth-client-id', 'new-client', '--oauth-client-secret-env', 'OTHER_SECRET', '--oauth-issuer', 'https://auth.example.org']); + expect(configManager.getServer('oauth')?.auth).toMatchObject({ clientId: 'new-client', clientSecretEnv: 'OTHER_SECRET' }); + }); + it('rejects incomplete OAuth and options that would otherwise be silently ignored', async () => { + await run(['add', 'bad', '--type', 'http', '--url', 'https://example.org/mcp', '--oauth-client-id', 'client']); + expect(process.exitCode).toBe(1); + await run(['add', 'bad', '--command', 'node', '--header', 'X-Token=value']); + expect(configManager.listServers()).toEqual([]); + }); +}); diff --git a/src/tests/unit/tools.test.ts b/src/tests/unit/tools.test.ts index a4a6b5b..c8b497f 100644 --- a/src/tests/unit/tools.test.ts +++ b/src/tests/unit/tools.test.ts @@ -1,189 +1,67 @@ -import { describe, it, expect } from 'vitest'; - -describe('tools command', () => { - describe('tool schema structure validation', () => { - // 由于 printProperty 是内部函数,我们通过实际输出来测试其行为 - // 这些测试确保嵌套对象、数组和枚举值能正确显示 - - it('should display nested object properties', () => { - // 这里需要模拟完整的 tools 命令调用 - // 由于 printProperty 是内部函数,我们测试最终输出 - const mockTool = { - name: 'test_tool', - description: 'Test tool with nested objects', - inputSchema: { - type: 'object', - properties: { - params: { - type: 'object', - description: 'Nested parameters', - properties: { - lang: { - type: 'number', - description: 'Language code' - } - }, - required: ['lang'] - }, - simple: { - type: 'string', - description: 'Simple parameter' - } - }, - required: ['params'] - } - }; - - // 验证 schema 结构正确 - expect(mockTool.inputSchema.properties.params).toBeDefined(); - expect(mockTool.inputSchema.properties.params.type).toBe('object'); - expect(mockTool.inputSchema.properties.params.properties).toBeDefined(); - expect(mockTool.inputSchema.properties.params.properties.lang).toBeDefined(); - }); - - it('should handle array types with items', () => { - const mockSchema = { - type: 'object', - properties: { - items: { - type: 'array', - items: { - type: 'string' - }, - description: 'List of items' - } - } - }; - - expect(mockSchema.properties.items.type).toBe('array'); - expect(mockSchema.properties.items.items).toBeDefined(); - expect(mockSchema.properties.items.items.type).toBe('string'); - }); - - it('should handle enum values', () => { - const mockSchema = { - type: 'object', - properties: { - format: { - type: 'string', - enum: ['jpeg', 'png', 'webp'], - description: 'Image format' - } - } - }; - - expect(mockSchema.properties.format.enum).toBeDefined(); - expect(mockSchema.properties.format.enum).toEqual(['jpeg', 'png', 'webp']); - }); - - it('should handle required fields marking', () => { - const mockSchema = { - type: 'object', - properties: { - required_field: { - type: 'string' - }, - optional_field: { - type: 'number' - } - }, - required: ['required_field'] - }; - - expect(mockSchema.required).toContain('required_field'); - expect(mockSchema.required).not.toContain('optional_field'); - }); +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { Command } from 'commander'; +vi.mock('../../core/config.js', () => ({ configManager: { getServer: vi.fn() } })); +vi.mock('../../core/daemon-client.js', () => ({ + DaemonClient: { ensureDaemon: vi.fn(), listTools: vi.fn() }, +})); +import { configManager } from '../../core/config.js'; +import { DaemonClient } from '../../core/daemon-client.js'; +import { registerToolsCommand } from '../../commands/tools.js'; + +describe('actual tools command rendering and filtering', () => { + let previousExitCode: typeof process.exitCode; + beforeEach(() => { + previousExitCode = process.exitCode; process.exitCode = 0; + vi.mocked(configManager.getServer).mockReturnValue({ name: 'server', command: 'node' }); + vi.mocked(DaemonClient.listTools).mockResolvedValue([{ + name: 'nested_tool', description: 'Nested tool', + inputSchema: { type: 'object', required: ['settings'], properties: { + settings: { type: 'object', required: ['language'], properties: { language: { type: 'string', enum: ['en', 'zh'] } } }, + items: { type: 'array', items: { type: 'number' } }, + } }, + }, { name: 'other_tool', inputSchema: { type: 'object', properties: {} } }]); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); }); - - describe('complex nested structures', () => { - it('should handle deeply nested objects', () => { - const mockSchema = { - type: 'object', - properties: { - level1: { - type: 'object', - properties: { - level2: { - type: 'object', - properties: { - value: { - type: 'string', - description: 'Deep value' - } - } - } - } - } - } - }; - - expect(mockSchema.properties.level1.properties.level2.properties.value).toBeDefined(); - expect(mockSchema.properties.level1.properties.level2.properties.value.type).toBe('string'); - }); - - it('should handle arrays with complex item types', () => { - const mockSchema = { - type: 'object', - properties: { - complexArray: { - type: 'array', - items: { - type: 'object', - properties: { - name: { type: 'string' }, - count: { type: 'number' } - } - } - } - } - }; - - expect(mockSchema.properties.complexArray.items).toBeDefined(); - expect(mockSchema.properties.complexArray.items.type).toBe('object'); - }); + afterEach(() => { process.exitCode = previousExitCode; vi.restoreAllMocks(); vi.clearAllMocks(); }); + const run = async (...args: string[]) => { + const program = new Command().exitOverride(); + registerToolsCommand(program); + await program.parseAsync(['node', 'mcps', 'tools', 'server', ...args]); + }; + const output = () => vi.mocked(console.log).mock.calls.flat().join('\n'); + it('renders nested properties, required fields, arrays and enum values', async () => { + await run(); + expect(output()).toContain('settings*: object'); + expect(output()).toContain('language*: string ["en", "zh"]'); + expect(output()).toContain('items: array of number'); + expect(DaemonClient.listTools).toHaveBeenCalledWith('server'); }); - - describe('edge cases', () => { - it('should handle properties without type', () => { - const mockSchema: any = { - type: 'object', - properties: { - untyped: { - description: 'Field without explicit type' - } - } - }; - - expect(mockSchema.properties.untyped).toBeDefined(); - expect(mockSchema.properties.untyped.type).toBeUndefined(); - }); - - it('should handle empty objects', () => { - const mockSchema = { - type: 'object', - properties: { - empty: { - type: 'object', - properties: {} - } - } - }; - - expect(mockSchema.properties.empty.properties).toEqual({}); - }); - - it('should handle arrays without items specification', () => { - const mockSchema: any = { - type: 'object', - properties: { - arrayWithoutItems: { - type: 'array' - } - } - }; - - expect(mockSchema.properties.arrayWithoutItems.type).toBe('array'); - expect(mockSchema.properties.arrayWithoutItems.items).toBeUndefined(); - }); + it('filters names case-insensitively and supports simple output', async () => { + await run('--tool', 'NESTED', '--simple'); + expect(output()).toContain('nested_tool'); + expect(output()).not.toContain('other_tool'); + expect(output()).toContain('Total: 1'); + }); + it('outputs an actual JSON array', async () => { + await run('--json'); + expect(JSON.parse(output()).map((tool: any) => tool.name)).toEqual(['nested_tool', 'other_tool']); + }); + it('keeps empty JSON output parseable', async () => { + vi.mocked(DaemonClient.listTools).mockResolvedValue([]); + await run('--json'); + expect(JSON.parse(output())).toEqual([]); + }); + it('does not start or connect disabled servers', async () => { + vi.mocked(configManager.getServer).mockReturnValue({ name: 'server', command: 'node', disabled: true }); + await run(); + expect(process.exitCode).toBe(1); + expect(DaemonClient.ensureDaemon).not.toHaveBeenCalled(); + }); + it('returns failure when discovery fails', async () => { + vi.mocked(DaemonClient.listTools).mockRejectedValue(new Error('connection failed')); + await run(); + expect(process.exitCode).toBe(1); + expect(console.error).toHaveBeenCalledWith(expect.stringContaining('connection failed')); }); }); diff --git a/src/types/config.ts b/src/types/config.ts index 3934842..e2b4b51 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -1,35 +1,47 @@ import { z } from 'zod'; +const CommonServerFields = { + protocolVersion: z.enum(['auto', 'legacy', '2026-07-28']).optional(), + disabled: z.boolean().optional(), + autoApprove: z.array(z.string()).optional(), +}; + // Standard MCP server configuration (stdio type) export const StdioServerConfigSchema = z.object({ - command: z.string(), + command: z.string().trim().min(1), + type: z.literal('stdio').optional(), args: z.array(z.string()).optional(), env: z.record(z.string()).optional(), cwd: z.string().optional(), - disabled: z.boolean().optional(), - autoApprove: z.array(z.string()).optional(), + ...CommonServerFields, }).passthrough(); // Standard MCP server configuration (sse/http type) export const HttpServerConfigSchema = z.object({ - url: z.string().url(), + url: z.string().url().refine(value => /^https?:\/\//i.test(value), 'URL must use HTTP or HTTPS'), type: z.enum(['sse', 'streamableHttp', 'http']).optional(), headers: z.record(z.string()).optional(), - disabled: z.boolean().optional(), - autoApprove: z.array(z.string()).optional(), + auth: z.object({ + type: z.literal('client_credentials'), + clientId: z.string().min(1), + clientSecretEnv: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), + issuer: z.string().url(), + scope: z.string().optional(), + }).optional(), + ...CommonServerFields, }).passthrough(); // Union of all server config types export const ServerConfigSchema = z.union([ StdioServerConfigSchema, HttpServerConfigSchema, -]); +]).refine(config => !(('command' in config) && ('url' in config)), 'A server cannot have both command and url'); // Standard MCP config format (mcpServers) export const ConfigSchema = z.object({ mcpServers: z.record(z.string(), ServerConfigSchema), - daemonTimeout: z.number().optional(), -}); + daemonTimeout: z.number().int().positive().optional(), +}).passthrough(); export type StdioServerConfig = z.infer; export type HttpServerConfig = z.infer; @@ -38,6 +50,9 @@ export type Config = z.infer; // Helper to detect server type from config export function detectServerType(config: ServerConfig): 'stdio' | 'sse' | 'http' { + if (config.type === 'sse') return 'sse'; + if (config.type === 'http' || config.type === 'streamableHttp') return 'http'; + if (config.type === 'stdio') return 'stdio'; if ('url' in config && typeof config.url === 'string') { return config.url.includes('/sse') || config.url.endsWith('/sse') ? 'sse' : 'http'; } diff --git a/vitest.config.ts b/vitest.config.ts index 54d42f9..29b9977 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -4,6 +4,7 @@ export default defineConfig({ test: { globals: true, environment: 'node', + globalSetup: ['src/tests/global-setup.ts'], include: ['src/**/*.test.ts', 'src/**/*.spec.ts'], exclude: [ 'dist/**', @@ -12,6 +13,14 @@ export default defineConfig({ coverage: { provider: 'v8', reporter: ['text', 'json', 'html'], + thresholds: { + lines: 70, + statements: 70, + branches: 60, + functions: 75, + 'src/core/config.ts': { lines: 90, branches: 90 }, + 'src/core/client.ts': { lines: 90, branches: 75 }, + }, include: ['src/**/*.ts'], exclude: [ 'src/**/*.test.ts',