From 3c0294a1b90f3552e5c103a6466fce74515bd536 Mon Sep 17 00:00:00 2001 From: Nivesh353 Date: Wed, 17 Jun 2026 19:52:20 +0530 Subject: [PATCH] feat(mcp): add MCP client support Connect to MCP servers declared in agent.yaml / SDK mcpServers, register their tools as native AgentTools (namespaced __), and tear connections down on exit. stdio + HTTP + SSE transports, pagination, name sanitization, abort forwarding, fail-soft connect, recursive JSON Schema conversion. Fully opt-in; SDK not loaded when unused. --- README.md | 64 +++ package-lock.json | 1091 +++++++++++++++++++++++++++++++++++++++++++- package.json | 1 + src/env-utils.ts | 31 ++ src/exports.ts | 1 + src/index.ts | 9 +- src/loader.ts | 2 + src/mcp/manager.ts | 254 +++++++++++ src/mcp/types.ts | 31 ++ src/plugins.ts | 3 +- src/sdk-types.ts | 3 + src/sdk.ts | 14 + src/tool-loader.ts | 76 ++- test/mcp.test.ts | 167 +++++++ 14 files changed, 1721 insertions(+), 26 deletions(-) create mode 100644 src/env-utils.ts create mode 100644 src/mcp/manager.ts create mode 100644 src/mcp/types.ts create mode 100644 test/mcp.test.ts diff --git a/README.md b/README.md index c684c6d..209c507 100644 --- a/README.md +++ b/README.md @@ -579,6 +579,70 @@ my-plugin/ └── index.ts # Programmatic entry point ``` +## MCP (Model Context Protocol) + +Gitagent is an **MCP client**: point it at any [MCP server](https://modelcontextprotocol.io) and that server's tools are automatically discovered and made available to the agent — no integration code to write. This unlocks the whole ecosystem of ready-made servers (filesystem, GitHub, Postgres, Slack, fetch, …). + +### Configure servers in `agent.yaml` + +```yaml +mcp_servers: + filesystem: # local server over stdio (default) + command: npx + args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/data"] + env: + LOG_LEVEL: "${MCP_LOG_LEVEL}" # ${VAR} interpolated from the environment + timeoutMs: 30000 # connect/list timeout (default 30000) + + analytics: # remote server over Streamable HTTP + type: http + url: "https://mcp.example.com/mcp" + headers: + Authorization: "Bearer ${ANALYTICS_TOKEN}" + + legacy: # legacy SSE transport (deprecated) + type: sse + url: "https://old.example.com/sse" +``` + +On startup gitagent connects to each server, lists its tools, and registers them as **`__`** (e.g. `filesystem__read_file`, `analytics__query`). Connections are torn down automatically when the session ends. + +| Field | Applies to | Description | +|---|---|---| +| `command` / `args` / `env` / `cwd` | stdio | How to launch a local server | +| `type: http \| sse` + `url` + `headers` | remote | Connect to a remote server | +| `timeoutMs` | both | Connect + list-tools timeout (default `30000`) | + +### Use via the SDK + +```typescript +import { query } from "gitagent"; + +for await (const msg of query({ + prompt: "Summarize last week's signups from the database", + mcpServers: { + postgres: { + command: "npx", + args: ["-y", "@modelcontextprotocol/server-postgres", process.env.DB_URL!], + }, + }, +})) { + if (msg.type === "tool_use") console.log(`calling ${msg.toolName}`); +} +``` + +SDK `mcpServers` are merged with any `agent.yaml` `mcp_servers` (the SDK value wins on a key collision). + +### Behavior & guarantees + +- **Fail-soft:** a server that can't start (or times out) is logged and skipped — other servers and built-in tools keep working. +- **Namespaced & sanitized:** tool names are prefixed with the server name and cleaned to satisfy provider naming rules. +- **Pagination:** servers that paginate their tool list are fully enumerated. +- **Cleanup:** stdio servers (child processes) are shut down on every exit path (normal, `/quit`, Ctrl+C, error). +- **Lazy:** if no servers are configured, the MCP SDK is never loaded. + +> Note: v1 supports MCP **tools**. Resources and prompts are not yet exposed. + ## Multi-Model Support Gitagent works with any LLM provider supported by [pi-ai](https://github.com/badlogic/pi-mono/tree/main/packages/ai): diff --git a/package-lock.json b/package-lock.json index 1e81523..ecec55a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@googleworkspace/cli": "^0.8.1", "@mariozechner/pi-agent-core": "^0.70.2", "@mariozechner/pi-ai": "^0.70.2", + "@modelcontextprotocol/sdk": "^1.29.0", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.215.0", "@opentelemetry/exporter-trace-otlp-http": "^0.215.0", @@ -1167,6 +1168,18 @@ "integrity": "sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==", "license": "BSD-3-Clause" }, + "node_modules/@hono/node-server": { + "version": "1.19.14", + "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz", + "integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==", + "license": "MIT", + "engines": { + "node": ">=18.14.1" + }, + "peerDependencies": { + "hono": "^4" + } + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -1740,6 +1753,46 @@ "zod-to-json-schema": "^3.25.0" } }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.29.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz", + "integrity": "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ==", + "license": "MIT", + "dependencies": { + "@hono/node-server": "^1.19.9", + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.2.1", + "express-rate-limit": "^8.2.1", + "hono": "^4.11.4", + "jose": "^6.1.3", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } + } + }, "node_modules/@nodable/entities": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz", @@ -2954,6 +3007,19 @@ "@types/node": "*" } }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/acorn": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", @@ -2984,6 +3050,39 @@ "node": ">= 14" } }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -3122,6 +3221,43 @@ "node": "*" } }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/bowser": { "version": "2.14.1", "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", @@ -3134,6 +3270,15 @@ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", "license": "BSD-3-Clause" }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/cacheable": { "version": "2.3.5", "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.3.5.tgz", @@ -3147,6 +3292,35 @@ "qified": "^0.10.1" } }, + "node_modules/call-bind-apply-helpers": { + "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==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/chalk": { "version": "5.6.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", @@ -3197,6 +3371,19 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "license": "MIT" }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/content-type": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", @@ -3206,6 +3393,55 @@ "node": ">= 0.6" } }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/cors": { + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/curve25519-js": { "version": "0.0.4", "resolved": "https://registry.npmjs.org/curve25519-js/-/curve25519-js-0.0.4.tgz", @@ -3252,15 +3488,39 @@ "node": ">= 14" } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", "license": "Apache-2.0", + "peer": true, "engines": { "node": ">=8" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/ecdsa-sig-formatter": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", @@ -3270,12 +3530,57 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "license": "MIT" }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -3285,6 +3590,12 @@ "node": ">=6" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, "node_modules/escodegen": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", @@ -3337,18 +3648,131 @@ "node": ">=0.10.0" } }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/eventemitter3": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", "license": "MIT" }, + "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/eventsource-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.0.tgz", + "integrity": "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz", + "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.2.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "license": "MIT" }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/fast-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", + "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fast-xml-builder": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz", @@ -3427,6 +3851,27 @@ "url": "https://github.com/sindresorhus/file-type?sponsor=1" } }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/formdata-polyfill": { "version": "4.0.10", "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", @@ -3439,8 +3884,35 @@ "node": ">=12.20.0" } }, - "node_modules/gaxios": { - "version": "7.1.4", + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gaxios": { + "version": "7.1.4", "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-7.1.4.tgz", "integrity": "sha512-bTIgTsM2bWn3XklZISBTQX7ZSddGW+IO3bMdGaemHZ3tbqExMENHLx6kKZ/KlejgrMtj8q7wBItt51yegqalrA==", "license": "Apache-2.0", @@ -3476,6 +3948,43 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/get-uri": { "version": "6.0.5", "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz", @@ -3525,6 +4034,30 @@ "node": ">=14" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/hashery": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", @@ -3537,12 +4070,53 @@ "node": ">=20" } }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hono": { + "version": "4.12.25", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.25.tgz", + "integrity": "sha512-2NFaIyNVgJmBs/ecmtGzlmluTFs5cHEWGTdu0t1HBwYzoGXOL5nUQBRMXsXWla5i4KkG//QMzVP88m1+I3fdAQ==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, "node_modules/hookified": { "version": "1.15.1", "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", "license": "MIT" }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", @@ -3569,6 +4143,22 @@ "node": ">= 14" } }, + "node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/ieee754": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", @@ -3604,6 +4194,12 @@ "node": ">=18" } }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, "node_modules/ip-address": { "version": "10.2.0", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", @@ -3613,6 +4209,15 @@ "node": ">= 12" } }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -3622,6 +4227,27 @@ "node": ">=8" } }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.3.tgz", + "integrity": "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-yaml": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", @@ -3656,6 +4282,18 @@ "node": ">=16" } }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, + "node_modules/json-schema-typed": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", + "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", + "license": "BSD-2-Clause" + }, "node_modules/jwa": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", @@ -3717,6 +4355,15 @@ "node": "20 || >=22" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/media-typer": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", @@ -3726,6 +4373,43 @@ "node": ">= 0.8" } }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/module-details-from-path": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", @@ -3769,6 +4453,15 @@ "node": ">=18" } }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/netmask": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz", @@ -3828,6 +4521,27 @@ "url": "https://opencollective.com/node-fetch" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/on-exit-leak-free": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", @@ -3837,6 +4551,27 @@ "node": ">=14.0.0" } }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, "node_modules/openai": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/openai/-/openai-6.26.0.tgz", @@ -3931,6 +4666,15 @@ "node": ">= 14" } }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/partial-json": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/partial-json/-/partial-json-0.1.7.tgz", @@ -3952,6 +4696,25 @@ "node": ">=14.0.0" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/pino": { "version": "9.14.0", "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz", @@ -3989,6 +4752,15 @@ "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", "license": "MIT" }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/process-warning": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", @@ -4029,6 +4801,19 @@ "node": ">=12.0.0" } }, + "node_modules/proxy-addr": { + "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==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/proxy-agent": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", @@ -4081,12 +4866,51 @@ "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", "license": "MIT" }, + "node_modules/qs": { + "version": "6.15.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz", + "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/quick-format-unescaped": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", "license": "MIT" }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/real-require": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", @@ -4105,6 +4929,15 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/require-in-the-middle": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz", @@ -4127,6 +4960,22 @@ "node": ">= 4" } }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -4156,6 +5005,12 @@ "node": ">=10" } }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, "node_modules/semver": { "version": "7.8.1", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.1.tgz", @@ -4169,6 +5024,57 @@ "node": ">=10" } }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, "node_modules/sharp": { "version": "0.34.5", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", @@ -4214,6 +5120,99 @@ "@img/sharp-win32-x64": "0.34.5" } }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "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==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", @@ -4280,6 +5279,15 @@ "node": ">= 10.x" } }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -4343,6 +5351,15 @@ "real-require": "^0.2.0" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, "node_modules/token-types": { "version": "6.1.2", "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz", @@ -4373,6 +5390,37 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/typebox": { "version": "1.1.38", "resolved": "https://registry.npmjs.org/typebox/-/typebox-1.1.38.tgz", @@ -4420,6 +5468,15 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "license": "MIT" }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", @@ -4430,6 +5487,15 @@ "uuid": "dist/bin/uuid" } }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/web-streams-polyfill": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", @@ -4445,6 +5511,21 @@ "integrity": "sha512-yYO1qSs0Fe7tGtnxOFHomocUD6IZtoAgmA4oDFyGIRZ67D3QZk3w7swA6XXFXNQngiyrg2k7tul6IrM3eUFh7A==", "license": "MIT" }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/win-guid": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/win-guid/-/win-guid-0.2.1.tgz", @@ -4468,6 +5549,12 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + }, "node_modules/ws": { "version": "8.21.0", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", diff --git a/package.json b/package.json index 1ca9522..fe325be 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "@googleworkspace/cli": "^0.8.1", "@mariozechner/pi-agent-core": "^0.70.2", "@mariozechner/pi-ai": "^0.70.2", + "@modelcontextprotocol/sdk": "^1.29.0", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.215.0", "@opentelemetry/exporter-trace-otlp-http": "^0.215.0", diff --git a/src/env-utils.ts b/src/env-utils.ts new file mode 100644 index 0000000..ca08d3b --- /dev/null +++ b/src/env-utils.ts @@ -0,0 +1,31 @@ +/** + * Shared `${VAR}` environment-variable interpolation. + * + * Replaces `${VAR_NAME}` occurrences in strings with `process.env.VAR_NAME`, + * or an empty string when the variable is unset (matching the long-standing + * plugin-config behavior). Recurses through arrays and plain objects so an + * entire config object (e.g. an MCP server definition) can be interpolated in + * one call. Non-string leaf values are returned unchanged. + */ +const ENV_VAR_PATTERN = /\$\{(\w+)\}/g; + +export function interpolateEnvString(value: string): string { + return value.replace(ENV_VAR_PATTERN, (_, envName) => process.env[envName] || ""); +} + +export function interpolateEnv(value: T): T { + if (typeof value === "string") { + return interpolateEnvString(value) as unknown as T; + } + if (Array.isArray(value)) { + return value.map((item) => interpolateEnv(item)) as unknown as T; + } + if (value && typeof value === "object") { + const out: Record = {}; + for (const [key, v] of Object.entries(value as Record)) { + out[key] = interpolateEnv(v); + } + return out as unknown as T; + } + return value; +} diff --git a/src/exports.ts b/src/exports.ts index 2748236..5c9dd03 100644 --- a/src/exports.ts +++ b/src/exports.ts @@ -23,6 +23,7 @@ export type { // Internal types (for advanced usage) export type { AgentManifest, LoadedAgent } from "./loader.js"; +export type { McpServerConfig } from "./mcp/types.js"; export type { SkillMetadata } from "./skills.js"; export type { WorkflowMetadata } from "./workflows.js"; export type { SubAgentMetadata } from "./agents.js"; diff --git a/src/index.ts b/src/index.ts index 2c09693..7688504 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ import { expandSkillCommand, refreshSkills } from "./skills.js"; import { loadHooksConfig, runHooks, wrapToolWithHooks } from "./hooks.js"; import type { HooksConfig } from "./hooks.js"; import { loadDeclarativeTools } from "./tool-loader.js"; +import { setupMcp } from "./mcp/manager.js"; import { toAgentTool } from "./tool-utils.js"; import { AuditLogger, isAuditEnabled } from "./audit.js"; import { formatComplianceWarnings } from "./compliance.js"; @@ -541,6 +542,10 @@ async function main(): Promise { } } + // MCP tools (manifest-declared servers) + const mcpSetup = await setupMcp(manifest.mcp_servers, existingToolNames); + tools.push(...mcpSetup.tools); + // Wrap with hooks if configured if (hooksConfig) { tools = tools.map((t) => wrapToolWithHooks(t, hooksConfig, agentDir, sessionId)); @@ -633,6 +638,7 @@ async function main(): Promise { } throw err; } finally { + await mcpSetup.cleanup().catch(() => {}); if (localSession) { console.log(dim("Finalizing session...")); localSession.finalize(); @@ -667,6 +673,7 @@ async function main(): Promise { if (trimmed === "/quit" || trimmed === "/exit") { rl.close(); + await mcpSetup.cleanup().catch(() => {}); if (localSession) { console.log(dim("Finalizing session...")); localSession.finalize(); @@ -818,7 +825,7 @@ async function main(): Promise { try { _session.end({ "gitagent.cost_usd": _totalCostUsd }); } catch { /* ignore */ } - stopSandbox().finally(() => process.exit(0)); + Promise.all([mcpSetup.cleanup(), stopSandbox()]).finally(() => process.exit(0)); } }); diff --git a/src/loader.ts b/src/loader.ts index b8d193e..3fe06ba 100644 --- a/src/loader.ts +++ b/src/loader.ts @@ -22,6 +22,7 @@ import type { ComplianceWarning } from "./compliance.js"; import { discoverAndLoadPlugins } from "./plugins.js"; import type { LoadedPlugin } from "./plugin-types.js"; import type { PluginConfig } from "./plugin-types.js"; +import type { McpServerConfig } from "./mcp/types.js"; export interface AgentManifest { spec_version: string; @@ -55,6 +56,7 @@ export interface AgentManifest { delegation?: { mode: "auto" | "explicit" | "router"; router?: string }; compliance?: Record; plugins?: Record; + mcp_servers?: Record; } async function readFileOr(path: string, fallback: string): Promise { diff --git a/src/mcp/manager.ts b/src/mcp/manager.ts new file mode 100644 index 0000000..c54ac09 --- /dev/null +++ b/src/mcp/manager.ts @@ -0,0 +1,254 @@ +import { buildTool } from "../tool-factory.js"; +import { interpolateEnv } from "../env-utils.js"; +import type { AgentTool } from "@mariozechner/pi-agent-core"; +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import type { McpServerConfig, McpStdioServerConfig, McpSetupResult } from "./types.js"; + +const DEFAULT_TIMEOUT_MS = 30000; + +/** A live connection to one MCP server. */ +interface McpConnection { + name: string; + client: Client; + close: () => Promise; +} + +function withTimeout(op: Promise, ms: number, label: string): Promise { + return Promise.race([ + op, + new Promise((_, reject) => + setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms), + ), + ]); +} + +/** + * Flatten an MCP tool result (an array of content blocks plus an optional + * `isError` flag) into the plain string that an AgentTool's execute() returns. + * Binary blocks are summarized rather than inlined to protect the token budget. + */ +export function flattenToolResult(result: any): string { + const blocks: any[] = Array.isArray(result?.content) ? result.content : []; + const parts: string[] = []; + for (const block of blocks) { + switch (block?.type) { + case "text": + parts.push(String(block.text ?? "")); + break; + case "image": + parts.push(`[image: ${block.mimeType || "unknown"}, data omitted]`); + break; + case "audio": + parts.push(`[audio: ${block.mimeType || "unknown"}, data omitted]`); + break; + case "resource": { + const res = block.resource ?? {}; + if (typeof res.text === "string") parts.push(res.text); + else parts.push(`[resource: ${res.uri || "unknown"} (${res.mimeType || "binary"})]`); + break; + } + case "resource_link": + parts.push(`[resource_link: ${block.uri || "unknown"}]`); + break; + default: + if (block?.text) parts.push(String(block.text)); + break; + } + } + let text = parts.join("\n"); + // Some tools (those with an outputSchema) return only `structuredContent` + // with no text blocks — fall back to its JSON so the model isn't handed "". + if (!text && result?.structuredContent !== undefined) { + try { + text = JSON.stringify(result.structuredContent); + } catch { + /* leave text empty if not serializable */ + } + } + return result?.isError ? `Error: ${text}` : text; +} + +/** + * Make a tool name safe for LLM provider APIs, which require names to match + * roughly `^[a-zA-Z0-9_-]{1,64}$` (OpenAI/Anthropic). Invalid characters become + * `_`; names longer than 64 chars are truncated. Collisions after truncation + * are caught by the existing-name check in setupMcp. + */ +function sanitizeToolName(name: string): string { + const cleaned = name.replace(/[^a-zA-Z0-9_-]/g, "_"); + return cleaned.length > 64 ? cleaned.slice(0, 64) : cleaned; +} + +/** List every tool a server offers, following pagination cursors to the end. */ +async function listAllTools(client: Client): Promise { + const all: any[] = []; + let cursor: string | undefined; + do { + const res = await client.listTools(cursor ? { cursor } : undefined); + all.push(...res.tools); + cursor = res.nextCursor; + } while (cursor); + return all; +} + +/** + * List a connected server's tools and convert each into an AgentTool. + * Tools are namespaced `__` (sanitized for provider name rules) + * to avoid collisions. Exported so tests can exercise conversion over an + * in-memory transport without spawning. + */ +export async function buildToolsForConnection(conn: McpConnection): Promise[]> { + const tools = await listAllTools(conn.client); + return tools.map((t) => + buildTool({ + name: sanitizeToolName(`${conn.name}__${t.name}`), + description: t.description || `MCP tool ${t.name} from ${conn.name}`, + // MCP inputSchema is a JSON-Schema object ({type, properties, required}). + // buildTypeboxSchema converts it recursively (integers, enums, typed + // arrays, nested objects); unknown shapes degrade to Type.Any. + parameters: (t.inputSchema as Record) ?? {}, + execute: async (args: any, signal?: AbortSignal) => { + try { + // Forward the agent's abort signal so cancelling the turn cancels + // the in-flight MCP request. Call with the original (unsanitized) name. + const result = await conn.client.callTool( + { name: t.name, arguments: args ?? {} }, + undefined, + { signal }, + ); + return flattenToolResult(result); + } catch (err: any) { + // Protocol-level errors (e.g. -32602) throw; surface them as a + // string so the agent can read and recover instead of crashing. + return `Error: ${err?.message || err}`; + } + }, + // We can't know a remote tool's semantics — fail closed. + metadata: { isConcurrencySafe: false, isReadOnly: false, isDestructive: false }, + }), + ); +} + +/** Connect to a single server. Fail-soft: logs and returns null on any error. */ +async function connectServer(name: string, rawCfg: McpServerConfig): Promise { + const cfg = interpolateEnv(rawCfg); + const timeoutMs = cfg.timeoutMs ?? DEFAULT_TIMEOUT_MS; + try { + const { Client } = await import("@modelcontextprotocol/sdk/client/index.js"); + + let transport: any; + if (cfg.type === "http") { + if (!cfg.url) throw new Error("http server requires a url"); + const { StreamableHTTPClientTransport } = await import( + "@modelcontextprotocol/sdk/client/streamableHttp.js" + ); + transport = new StreamableHTTPClientTransport(new URL(cfg.url), { + requestInit: cfg.headers ? { headers: cfg.headers } : undefined, + }); + } else if (cfg.type === "sse") { + if (!cfg.url) throw new Error("sse server requires a url"); + const { SSEClientTransport } = await import("@modelcontextprotocol/sdk/client/sse.js"); + transport = new SSEClientTransport(new URL(cfg.url), { + requestInit: cfg.headers ? { headers: cfg.headers } : undefined, + }); + } else { + const stdio = cfg as McpStdioServerConfig; + if (!stdio.command) throw new Error("stdio server requires a command"); + const { StdioClientTransport, getDefaultEnvironment } = await import( + "@modelcontextprotocol/sdk/client/stdio.js" + ); + transport = new StdioClientTransport({ + command: stdio.command, + args: stdio.args ?? [], + env: { ...getDefaultEnvironment(), ...(stdio.env ?? {}) }, + cwd: stdio.cwd, + }); + } + + const client = new Client({ name: "gitagent", version: "1.5.2" }, { capabilities: {} }); + try { + await withTimeout(client.connect(transport), timeoutMs, `[mcp:${name}] connect`); + } catch (connectErr) { + // connect() spawns the child process / opens the socket. If it fails or + // times out mid-handshake, close the transport so we don't leak the + // spawned process or connection. + try { await transport?.close?.(); } catch { /* best-effort */ } + throw connectErr; + } + + return { + name, + client, + close: async () => { + try { + await client.close(); + } catch { + /* best-effort */ + } + }, + }; + } catch (err: any) { + console.warn(`[mcp:${name}] failed to connect: ${err?.message || err} — skipping`); + return null; + } +} + +/** + * Connect to all configured MCP servers, register their tools, and return an + * idempotent cleanup. Servers connect in parallel and independently fail-soft — + * one bad server never blocks the others. Returns immediately with no work (and + * without loading the MCP SDK) when no servers are configured. + * + * @param servers merged server map (manifest + SDK options) + * @param existingToolNames running set of tool names already registered; used + * for collision detection and updated in place. + */ +export async function setupMcp( + servers: Record | undefined, + existingToolNames: Set, +): Promise { + const entries = Object.entries(servers ?? {}); + if (entries.length === 0) { + return { tools: [], cleanup: async () => {} }; + } + + const settled = await Promise.allSettled( + entries.map(([name, cfg]) => connectServer(name, cfg)), + ); + const connections = settled + .map((s) => (s.status === "fulfilled" ? s.value : null)) + .filter((c): c is McpConnection => c !== null); + + const tools: AgentTool[] = []; + for (const conn of connections) { + let built: AgentTool[]; + try { + built = await withTimeout( + buildToolsForConnection(conn), + DEFAULT_TIMEOUT_MS, + `[mcp:${conn.name}] listTools`, + ); + } catch (err: any) { + console.warn(`[mcp:${conn.name}] failed to list tools: ${err?.message || err} — skipping`); + await conn.close(); + continue; + } + for (const tool of built) { + if (existingToolNames.has(tool.name)) { + console.warn(`[mcp:${conn.name}] tool "${tool.name}" collides with an existing tool — skipping`); + continue; + } + existingToolNames.add(tool.name); + tools.push(tool); + } + } + + let closed = false; + const cleanup = async () => { + if (closed) return; + closed = true; + await Promise.allSettled(connections.map((c) => c.close())); + }; + + return { tools, cleanup }; +} diff --git a/src/mcp/types.ts b/src/mcp/types.ts new file mode 100644 index 0000000..a609d93 --- /dev/null +++ b/src/mcp/types.ts @@ -0,0 +1,31 @@ +import type { AgentTool } from "@mariozechner/pi-agent-core"; + +/** A local MCP server launched as a child process, spoken to over stdio. */ +export interface McpStdioServerConfig { + type?: "stdio"; + command: string; + args?: string[]; + env?: Record; + cwd?: string; + /** Connect + initial listTools timeout in ms. Default 30000. */ + timeoutMs?: number; +} + +/** A remote MCP server reached over Streamable HTTP (or legacy SSE). */ +export interface McpHttpServerConfig { + type: "http" | "sse"; + url: string; + headers?: Record; + /** Connect + initial listTools timeout in ms. Default 30000. */ + timeoutMs?: number; +} + +export type McpServerConfig = McpStdioServerConfig | McpHttpServerConfig; + +/** Result of wiring up all configured MCP servers for a session. */ +export interface McpSetupResult { + /** Tools discovered across all servers, namespaced `__`. */ + tools: AgentTool[]; + /** Idempotent teardown — closes every transport/client. Safe to call repeatedly. */ + cleanup: () => Promise; +} diff --git a/src/plugins.ts b/src/plugins.ts index 8a22899..5ab6171 100644 --- a/src/plugins.ts +++ b/src/plugins.ts @@ -4,6 +4,7 @@ import { execFileSync } from "child_process"; import { createRequire } from "module"; import { homedir } from "os"; import yaml from "js-yaml"; +import { interpolateEnvString } from "./env-utils.js"; import type { AgentTool } from "@mariozechner/pi-agent-core"; import type { PluginManifest, @@ -73,7 +74,7 @@ function resolvePluginConfig( let value = userConfig[key]; // Resolve ${ENV_VAR} syntax if (typeof value === "string") { - value = value.replace(/\$\{(\w+)\}/g, (_, envName) => process.env[envName] || ""); + value = interpolateEnvString(value); } resolved[key] = value; } else if (prop.env && process.env[prop.env]) { diff --git a/src/sdk-types.ts b/src/sdk-types.ts index 20dc060..5ab79ca 100644 --- a/src/sdk-types.ts +++ b/src/sdk-types.ts @@ -1,5 +1,6 @@ import type { AgentManifest } from "./loader.js"; import type { SessionCosts } from "./cost-tracker.js"; +import type { McpServerConfig } from "./mcp/types.js"; // ── Message types ────────────────────────────────────────────────────── @@ -145,6 +146,8 @@ export interface QueryOptions { maxTurns?: number; abortController?: AbortController; sessionId?: string; + /** MCP servers to connect to. Merged with manifest `mcp_servers` (these win on key collision). */ + mcpServers?: Record; constraints?: { temperature?: number; maxTokens?: number; diff --git a/src/sdk.ts b/src/sdk.ts index dfa9a80..55b941c 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -9,6 +9,8 @@ import type { SandboxContext } from "./sandbox.js"; import { loadHooksConfig, runHooks, wrapToolWithHooks } from "./hooks.js"; import { loadDeclarativeTools } from "./tool-loader.js"; import { toAgentTool } from "./tool-utils.js"; +import { setupMcp } from "./mcp/manager.js"; +import type { McpSetupResult } from "./mcp/types.js"; import { wrapToolWithProgrammaticHooks } from "./sdk-hooks.js"; import { mergeHooksConfigs } from "./plugins.js"; import { initLocalSession } from "./session.js"; @@ -109,6 +111,7 @@ export function query(options: QueryOptions): Query { // Sandbox context (hoisted for cleanup in catch) let sandboxCtx: SandboxContext | undefined; + let mcpSetup: McpSetupResult | undefined; // Local session (hoisted for cleanup in catch) let localSession: LocalSession | undefined; @@ -206,6 +209,11 @@ export function query(options: QueryOptions): Query { } } + // MCP tools — merge manifest + SDK server configs (SDK wins on key collision) + const mcpServers = { ...loaded.manifest.mcp_servers, ...options.mcpServers }; + mcpSetup = await setupMcp(mcpServers, existingToolNames); + tools = [...tools, ...mcpSetup.tools]; + // SDK-provided tools if (options.tools) { const converted = options.tools.map(toAgentTool); @@ -550,6 +558,12 @@ export function query(options: QueryOptions): Query { // Ensure channel finishes even if no agent_end event channel.finish(); } finally { + // Tear down MCP servers on every exit path — success, hook-block + // early-return, abort, and error (this finally runs before the + // .catch() handler below). cleanup() is idempotent. + if (mcpSetup) { + try { await mcpSetup.cleanup(); } catch { /* best-effort */ } + } // Close the session span on every exit path — success, hook-block // early-return, and the .catch() handler below (rethrow so this // runs first). diff --git a/src/tool-loader.ts b/src/tool-loader.ts index 5c58f02..13ac32d 100644 --- a/src/tool-loader.ts +++ b/src/tool-loader.ts @@ -16,35 +16,67 @@ interface ToolDefinition { }; } -export function buildTypeboxSchema(schema: Record): any { - // Convert a simplified JSON-schema-like object to Typebox properties +/** + * Recursively convert a JSON-Schema node into a TypeBox schema. Handles the + * full set of types tool authors and MCP servers use: string/number/integer/ + * boolean/null, enums (→ union of literals), typed arrays (real item type), + * nested objects (real properties + required), and union `type` arrays. Unknown + * or missing types degrade to `Type.Any()` so the call still goes through and + * the server validates the actual payload. + */ +function jsonSchemaToTypebox(def: any): any { + if (!def || typeof def !== "object") return Type.Any(); + const desc = def.description || ""; + const opts = desc ? { description: desc } : {}; + + // enum → union of literals (preserves the allowed values for the model) + if (Array.isArray(def.enum) && def.enum.length > 0) { + if (def.enum.length === 1) return Type.Literal(def.enum[0], opts); + return Type.Union(def.enum.map((v: any) => Type.Literal(v)), opts); + } + + // union type, e.g. ["string", "null"] + if (Array.isArray(def.type)) { + const variants = def.type.map((t: string) => jsonSchemaToTypebox({ ...def, type: t, description: undefined })); + return variants.length === 1 ? variants[0] : Type.Union(variants, opts); + } + + switch (def.type) { + case "string": + return Type.String(opts); + case "number": + return Type.Number(opts); + case "integer": + return Type.Integer(opts); + case "boolean": + return Type.Boolean(opts); + case "null": + return Type.Null(opts); + case "array": + return Type.Array(def.items ? jsonSchemaToTypebox(def.items) : Type.Any(), opts); + case "object": + return buildTypeboxSchema(def, opts); + default: + // No/unknown type — fall back to permissive Any. + return Type.Any(opts); + } +} + +/** + * Build a TypeBox object schema from a JSON-Schema-like object (with + * `properties` and `required`). Used for both declarative YAML tools and MCP + * tool input schemas. + */ +export function buildTypeboxSchema(schema: Record, opts: Record = {}): any { const properties: Record = {}; if (schema.properties) { for (const [key, def] of Object.entries(schema.properties) as [string, any][]) { - const desc = def.description || ""; const required = schema.required?.includes(key) ?? false; - let prop; - switch (def.type) { - case "number": - prop = Type.Number({ description: desc }); - break; - case "boolean": - prop = Type.Boolean({ description: desc }); - break; - case "array": - prop = Type.Array(Type.Any(), { description: desc }); - break; - case "object": - prop = Type.Any({ description: desc }); - break; - default: - prop = Type.String({ description: desc }); - break; - } + const prop = jsonSchemaToTypebox(def); properties[key] = required ? prop : Type.Optional(prop); } } - return Type.Object(properties); + return Type.Object(properties, opts); } function createDeclarativeTool( diff --git a/test/mcp.test.ts b/test/mcp.test.ts new file mode 100644 index 0000000..746b92d --- /dev/null +++ b/test/mcp.test.ts @@ -0,0 +1,167 @@ +import { describe, it, before } from "node:test"; +import assert from "node:assert/strict"; +import { z } from "zod"; + +// Dynamic imports since the project is ESM and tests run against compiled dist. +let buildToolsForConnection: typeof import("../dist/mcp/manager.js").buildToolsForConnection; +let flattenToolResult: typeof import("../dist/mcp/manager.js").flattenToolResult; +let setupMcp: typeof import("../dist/mcp/manager.js").setupMcp; +let Client: typeof import("@modelcontextprotocol/sdk/client/index.js").Client; +let McpServer: typeof import("@modelcontextprotocol/sdk/server/mcp.js").McpServer; +let InMemoryTransport: typeof import("@modelcontextprotocol/sdk/inMemory.js").InMemoryTransport; + +before(async () => { + const mgr = await import("../dist/mcp/manager.js"); + buildToolsForConnection = mgr.buildToolsForConnection; + flattenToolResult = mgr.flattenToolResult; + setupMcp = mgr.setupMcp; + Client = (await import("@modelcontextprotocol/sdk/client/index.js")).Client; + McpServer = (await import("@modelcontextprotocol/sdk/server/mcp.js")).McpServer; + InMemoryTransport = (await import("@modelcontextprotocol/sdk/inMemory.js")).InMemoryTransport; +}); + +/** Stand up an in-memory MCP server exposing echo/boom/pic tools, return a connected Client. */ +async function connectInMemoryServer() { + const server = new McpServer({ name: "test-server", version: "1.0.0" }); + + server.registerTool( + "echo", + { description: "Echo a message", inputSchema: { msg: z.string() } }, + async ({ msg }) => ({ content: [{ type: "text", text: msg }] }), + ); + server.registerTool( + "boom", + { description: "Always errors", inputSchema: {} }, + async () => ({ content: [{ type: "text", text: "kaboom" }], isError: true }), + ); + server.registerTool( + "pic", + { description: "Returns an image", inputSchema: {} }, + async () => ({ content: [{ type: "image", data: "AAAA", mimeType: "image/png" }] }), + ); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "test-client", version: "1.0.0" }, { capabilities: {} }); + await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]); + return { client, server }; +} + +describe("flattenToolResult", () => { + it("joins text blocks", () => { + assert.equal(flattenToolResult({ content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] }), "a\nb"); + }); + it("prefixes Error: when isError is true", () => { + assert.equal(flattenToolResult({ content: [{ type: "text", text: "bad" }], isError: true }), "Error: bad"); + }); + it("summarizes image blocks without inlining data", () => { + const out = flattenToolResult({ content: [{ type: "image", data: "AAAA", mimeType: "image/png" }] }); + assert.equal(out, "[image: image/png, data omitted]"); + assert.ok(!out.includes("AAAA")); + }); + it("handles embedded resource text and links", () => { + assert.equal(flattenToolResult({ content: [{ type: "resource", resource: { uri: "file://x", text: "hi" } }] }), "hi"); + assert.equal(flattenToolResult({ content: [{ type: "resource_link", uri: "file://y" }] }), "[resource_link: file://y]"); + }); + it("tolerates empty/malformed results", () => { + assert.equal(flattenToolResult({}), ""); + assert.equal(flattenToolResult(null), ""); + }); + it("falls back to structuredContent JSON when there are no text blocks", () => { + assert.equal( + flattenToolResult({ content: [], structuredContent: { count: 42 } }), + '{"count":42}', + ); + }); + it("prefers text content over structuredContent when both exist", () => { + assert.equal( + flattenToolResult({ content: [{ type: "text", text: "hi" }], structuredContent: { x: 1 } }), + "hi", + ); + }); +}); + +describe("buildToolsForConnection", () => { + it("namespaces tool names and wires execute through callTool", async () => { + const { client } = await connectInMemoryServer(); + const conn = { name: "srv", client, close: async () => { await client.close(); } }; + const tools = await buildToolsForConnection(conn as any); + + const names = tools.map((t) => t.name).sort(); + assert.deepEqual(names, ["srv__boom", "srv__echo", "srv__pic"]); + + const echo = tools.find((t) => t.name === "srv__echo")!; + const res = await echo.execute("call-1", { msg: "hello" }); + assert.equal(res.content[0].text, "hello"); + + const boom = tools.find((t) => t.name === "srv__boom")!; + const boomRes = await boom.execute("call-2", {}); + assert.match(boomRes.content[0].text, /^Error: /); + + const pic = tools.find((t) => t.name === "srv__pic")!; + const picRes = await pic.execute("call-3", {}); + assert.match(picRes.content[0].text, /\[image: image\/png/); + + await conn.close(); + }); +}); + +describe("buildToolsForConnection — pagination & name sanitization", () => { + it("follows nextCursor across pages and sanitizes/caps tool names", async () => { + // A mock client that paginates listTools across two pages. + const longName = "x".repeat(100); + const mockClient: any = { + async listTools(params: any) { + if (!params?.cursor) { + return { tools: [{ name: "do.it", inputSchema: {} }], nextCursor: "page2" }; + } + return { tools: [{ name: longName, inputSchema: {} }] }; // no nextCursor → end + }, + async callTool() { + return { content: [{ type: "text", text: "ok" }] }; + }, + }; + const tools = await buildToolsForConnection({ name: "srv", client: mockClient, close: async () => {} }); + + // both pages collected + assert.equal(tools.length, 2); + // invalid char "." sanitized to "_" + assert.equal(tools[0].name, "srv__do_it"); + // long name capped to 64 and only valid chars + assert.ok(tools[1].name.length <= 64); + assert.match(tools[1].name, /^[a-zA-Z0-9_-]+$/); + }); + + it("returns a clean 'Error:' string when callTool throws (protocol error)", async () => { + const mockClient: any = { + async listTools() { + return { tools: [{ name: "bad", inputSchema: {} }] }; + }, + async callTool() { + throw new Error("MCP error -32602: Invalid arguments"); + }, + }; + const tools = await buildToolsForConnection({ name: "srv", client: mockClient, close: async () => {} }); + const res = await tools[0].execute("c1", {}); + assert.match((res.content[0] as any).text, /^Error: .*-32602/); + }); +}); + +describe("setupMcp", () => { + it("returns empty tools and a no-op cleanup when no servers configured", async () => { + const result = await setupMcp(undefined, new Set()); + assert.deepEqual(result.tools, []); + // cleanup is idempotent / safe to call repeatedly + await result.cleanup(); + await result.cleanup(); + }); + + it("fails soft on an unreachable server (bad command) without throwing", async () => { + const existing = new Set(); + const result = await setupMcp( + { broken: { command: "definitely-not-a-real-binary-xyz", args: [], timeoutMs: 2000 } }, + existing, + ); + assert.deepEqual(result.tools, []); + await result.cleanup(); + }); +});