diff --git a/biome.json b/biome.json index 7c89d187e7..cd01eaa765 100644 --- a/biome.json +++ b/biome.json @@ -28,6 +28,7 @@ "packages/*/src/**/*.ts", "packages/*/test/**/*.ts", "packages/coding-agent/examples/**/*.ts", + "packages/coding-agent/extensions/**/*.ts", "!**/node_modules/**/*", "!**/test-sessions.ts", "!**/models.generated.ts", diff --git a/package-lock.json b/package-lock.json index 896bbfd529..a40fd7b8be 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,8 @@ "packages/coding-agent/examples/extensions/with-deps", "packages/coding-agent/examples/extensions/custom-provider-anthropic", "packages/coding-agent/examples/extensions/custom-provider-gitlab-duo", - "packages/coding-agent/examples/extensions/sandbox" + "packages/coding-agent/examples/extensions/sandbox", + "packages/coding-agent/extensions/prime-mcp" ], "dependencies": { "@earendil-works/pi-coding-agent": "^0.2.2", @@ -1189,6 +1190,18 @@ } } }, + "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/@jridgewell/sourcemap-codec": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", @@ -1378,6 +1391,105 @@ "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/@modelcontextprotocol/sdk/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/@modelcontextprotocol/sdk/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/@modelcontextprotocol/sdk/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/@modelcontextprotocol/sdk/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/@modelcontextprotocol/sdk/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/@napi-rs/wasm-runtime": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", @@ -2246,6 +2358,19 @@ "dev": true, "license": "MIT" }, + "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/agent-base": { "version": "7.1.4", "license": "MIT", @@ -2253,6 +2378,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": "6.2.2", "license": "MIT", @@ -2361,6 +2519,43 @@ "readable-stream": "^3.4.0" } }, + "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", @@ -2424,6 +2619,44 @@ "version": "1.0.1", "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/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/canvas": { "version": "3.2.3", "dev": true, @@ -2668,6 +2901,28 @@ "node": ">=12" } }, + "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", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -2675,6 +2930,41 @@ "dev": true, "license": "MIT" }, + "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": "6.0.6", "dev": true, @@ -2754,6 +3044,15 @@ "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", "dev": true, @@ -2771,6 +3070,20 @@ "node": ">=0.3.1" } }, + "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", "license": "Apache-2.0", @@ -2778,10 +3091,25 @@ "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", "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/end-of-stream": { "version": "1.4.5", "license": "MIT", @@ -2789,9 +3117,17 @@ "once": "^1.4.0" } }, + "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", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -2804,6 +3140,18 @@ "dev": true, "license": "MIT" }, + "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/esbuild": { "version": "0.28.1", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", @@ -2853,6 +3201,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", "license": "BSD-2-Clause", @@ -2907,6 +3261,36 @@ "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/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/execa": { "version": "1.0.0", "dev": true, @@ -2951,6 +3335,67 @@ "node": ">=12.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", "license": "MIT" @@ -2973,6 +3418,12 @@ "@types/yauzl": "^2.9.1" } }, + "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-glob": { "version": "3.3.3", "dev": true, @@ -2988,6 +3439,22 @@ "node": ">=8.6.0" } }, + "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", @@ -3088,6 +3555,27 @@ "node": ">=8" } }, + "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", "license": "MIT", @@ -3098,6 +3586,24 @@ "node": ">=12.20.0" } }, + "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/fs-constants": { "version": "1.0.0", "dev": true, @@ -3120,7 +3626,6 @@ }, "node_modules/function-bind": { "version": "1.1.2", - "dev": true, "license": "MIT", "funding": { "url": "https://github.com/sponsors/ljharb" @@ -3167,6 +3672,43 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "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-stream": { "version": "5.2.0", "license": "MIT", @@ -3252,6 +3794,18 @@ "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/graceful-fs": { "version": "4.2.11", "license": "ISC" @@ -3263,9 +3817,20 @@ "node": ">=8" } }, + "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/hasown": { "version": "2.0.3", - "dev": true, "license": "MIT", "dependencies": { "function-bind": "^1.1.2" @@ -3281,6 +3846,15 @@ "node": "*" } }, + "node_modules/hono": { + "version": "4.12.26", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.26.tgz", + "integrity": "sha512-uyZtpnYxM9CmQ7QsQknM4zN8EftNqhON1qYeIKM0Se67CCEe2c44xyGURwB0axX2fBDu1dqHrHAc1hmNT8ITkw==", + "license": "MIT", + "engines": { + "node": ">=16.9.0" + } + }, "node_modules/hosted-git-info": { "version": "9.0.3", "license": "ISC", @@ -3291,6 +3865,26 @@ "node": "^20.17.0 || >=22.9.0" } }, + "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", "license": "MIT", @@ -3317,14 +3911,30 @@ "version": "9.1.7", "dev": true, "license": "MIT", - "bin": { - "husky": "bin.js" + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, + "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": ">=18" + "node": ">=0.10.0" }, "funding": { - "url": "https://github.com/sponsors/typicode" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/ieee754": { @@ -3354,7 +3964,6 @@ }, "node_modules/inherits": { "version": "2.0.4", - "dev": true, "license": "ISC" }, "node_modules/ini": { @@ -3377,6 +3986,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-core-module": { "version": "2.16.2", "dev": true, @@ -3425,6 +4043,12 @@ "node": ">=0.12.0" } }, + "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/is-stream": { "version": "1.1.0", "dev": true, @@ -3435,7 +4059,6 @@ }, "node_modules/isexe": { "version": "2.0.0", - "dev": true, "license": "ISC" }, "node_modules/jiti": { @@ -3445,6 +4068,15 @@ "jiti": "lib/jiti-cli.mjs" } }, + "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/json-bigint": { "version": "1.0.0", "license": "MIT", @@ -3463,6 +4095,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", "license": "MIT", @@ -3781,6 +4425,36 @@ "node": ">= 18" } }, + "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", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "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/merge2": { "version": "1.4.1", "dev": true, @@ -3903,6 +4577,15 @@ "dev": true, "license": "MIT" }, + "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", "license": "MIT", @@ -3992,6 +4675,18 @@ "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/obug": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.2.tgz", @@ -4006,6 +4701,18 @@ "node": ">=12.20.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", "license": "ISC", @@ -4098,6 +4805,15 @@ "version": "6.0.1", "license": "MIT" }, + "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", "license": "MIT" @@ -4144,6 +4860,16 @@ "url": "https://github.com/sponsors/isaacs" } }, + "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/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -4189,6 +4915,15 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "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/postcss": { "version": "8.5.15", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", @@ -4243,6 +4978,10 @@ "node": ">=10" } }, + "node_modules/prime-agent-extension-mcp": { + "resolved": "packages/coding-agent/extensions/prime-mcp", + "link": true + }, "node_modules/proper-lockfile": { "version": "4.1.2", "license": "MIT", @@ -4283,6 +5022,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", "license": "MIT", @@ -4319,6 +5071,21 @@ "once": "^1.3.1" } }, + "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/queue-microtask": { "version": "1.2.3", "dev": true, @@ -4338,6 +5105,30 @@ ], "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/rc": { "version": "1.2.8", "dev": true, @@ -4382,6 +5173,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/resolve": { "version": "1.22.12", "dev": true, @@ -4452,6 +5252,22 @@ "@rolldown/binding-win32-x64-msvc": "1.0.3" } }, + "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/run-parallel": { "version": "1.2.0", "dev": true, @@ -4500,6 +5316,12 @@ ], "license": "MIT" }, + "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.7.4", "dev": true, @@ -4511,6 +5333,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/shebang-command": { "version": "1.2.0", "dev": true, @@ -4574,6 +5447,78 @@ "node": ">=18" } }, + "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/siginfo": { "version": "2.0.0", "dev": true, @@ -4681,6 +5626,15 @@ "dev": true, "license": "MIT" }, + "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/std-env": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz", @@ -4935,6 +5889,15 @@ "node": ">=8.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", "license": "MIT", @@ -5481,6 +6444,37 @@ "node": "*" } }, + "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", "license": "MIT" @@ -5520,6 +6514,15 @@ "version": "6.21.0", "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/util-deprecate": { "version": "1.0.2", "dev": true, @@ -5536,6 +6539,15 @@ "uuid": "dist-node/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/vite": { "version": "8.0.16", "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz", @@ -6124,6 +7136,19 @@ "@types/ms": "^2.1.0" } }, + "packages/coding-agent/extensions/prime-mcp": { + "name": "prime-agent-extension-mcp", + "version": "0.2.2", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.29.0" + }, + "peerDependencies": { + "@earendil-works/pi-ai": "*", + "@earendil-works/pi-coding-agent": "*", + "@earendil-works/pi-tui": "*", + "typebox": "*" + } + }, "packages/coding-agent/node_modules/@anthropic-ai/sdk": { "version": "0.52.0", "license": "MIT", diff --git a/package.json b/package.json index baed2c604d..430d0864fe 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,8 @@ "packages/coding-agent/examples/extensions/with-deps", "packages/coding-agent/examples/extensions/custom-provider-anthropic", "packages/coding-agent/examples/extensions/custom-provider-gitlab-duo", - "packages/coding-agent/examples/extensions/sandbox" + "packages/coding-agent/examples/extensions/sandbox", + "packages/coding-agent/extensions/prime-mcp" ], "scripts": { "clean": "npm run clean --workspaces", diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md index bf72b4f23d..ff23ad5284 100644 --- a/packages/coding-agent/CHANGELOG.md +++ b/packages/coding-agent/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- Added a first-party MCP (Model Context Protocol) client extension (`extensions/prime-mcp`) that reaches external stdio and HTTP MCP servers through a single token-efficient `mcp` proxy tool, with optional `directTools` promotion, lazy connect, idle disconnect, reconnect-on-failure, and a `/mcp` command. See [docs/mcp.md](docs/mcp.md). + ## [0.2.2] - 2026-06-25 - Added a bundled `websearch` skill (Google search via the Serper API) that loads by default. Add a Serper key via `/login` ("Serper (web search)"); it is stored with your other credentials and supplied to the skill automatically. The skill can be disabled with `bundledSkills.websearch: false` and overridden by a same-named skill in any user, project, package, or `--skill` location ([#86](https://github.com/PrimeIntellect-ai/prime-agent/issues/86)). diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md index 42f978011b..937a2e81f5 100644 --- a/packages/coding-agent/README.md +++ b/packages/coding-agent/README.md @@ -337,6 +337,8 @@ The default export can also be `async`. Prime Agent waits for async extension fa Place in `~/.prime/agent/extensions/`, `.prime/agent/extensions/`, or a [Prime Agent package](#prime-agent-packages) to share with others. See [docs/extensions.md](docs/extensions.md) and [examples/extensions/](examples/extensions/). +**MCP:** Prime Agent ships a first-party [Model Context Protocol](https://modelcontextprotocol.io) client extension that reaches external MCP servers (stdio or HTTP) through a single token-efficient proxy tool, with optional promotion of hot tools to first-class tools. See [docs/mcp.md](docs/mcp.md). + ### Themes Built-in: `dark`, `light`. Themes hot-reload: modify the active theme file and Prime Agent immediately applies changes. diff --git a/packages/coding-agent/docs/mcp.md b/packages/coding-agent/docs/mcp.md new file mode 100644 index 0000000000..83529ba8ab --- /dev/null +++ b/packages/coding-agent/docs/mcp.md @@ -0,0 +1,152 @@ +# MCP (Model Context Protocol) + +Prime Agent ships a first-party [MCP](https://modelcontextprotocol.io) client as a +pi extension. It lets the model call tools hosted by external MCP servers — over +stdio (local subprocess) or streamable HTTP (remote) — without loading every +server's tool schema into the prompt. + +The extension lives at `packages/coding-agent/extensions/prime-mcp/` and is +client-only: Prime Agent connects out to MCP servers; it does not expose itself +as an MCP server. + +## Why a proxy tool + +Loading every tool from every MCP server into the system prompt is expensive — +each tool carries a name, description, and full input schema. Instead, this +extension registers a single `mcp` tool. The model uses it to discover and call +tools on demand: + +| Action | Purpose | +| -------------- | ------------------------------------------------------------ | +| `list_servers` | List configured servers and their connection state. | +| `list_tools` | List a server's tools (name + first description line). | +| `describe` | Show one tool's full input schema before calling it. | +| `call` | Invoke a tool with an arguments object. | + +This keeps the always-on context cost to roughly one tool definition regardless +of how many servers or tools are configured. + +For a handful of frequently used tools you can opt into `directTools`, which +registers them as ordinary first-class tools (full schema, called directly) +while everything else stays behind the proxy. + +## Enabling the extension + +The extension is a pi package. Install it from this repo by local path: + +```bash +prime-agent install ./packages/coding-agent/extensions/prime-mcp +``` + +Or add it to `settings.json` under `extensions` / `packages` (see +[packages.md](packages.md)). To try it for a single run without installing: + +```bash +prime-agent -e ./packages/coding-agent/extensions/prime-mcp +``` + +It is not enabled by default in shipped settings. + +## Configuration + +Servers are declared in `mcp.json`-style files. The shape matches the +`mcpServers` object other MCP clients use, plus two Prime-specific keys. + +```json +{ + "mcpServers": { + "everything": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-everything"] + }, + "remote": { + "url": "https://example.com/mcp", + "headers": { "Authorization": "Bearer ${YOUR_TOKEN}" } + } + }, + "directTools": ["everything/echo"], + "idleTimeoutMs": 300000 +} +``` + +A server is **stdio** when it has a `command` (with optional `args`, `env`, +`cwd`) and **http** when it has a `url` (with optional `headers`). A working +template lives in +[`extensions/prime-mcp/mcp.json.example`](../extensions/prime-mcp/mcp.json.example). + +### File resolution and precedence + +Config is read from these paths, **highest precedence first**: + +1. `/.mcp.json` — project, the shared convention other tools also read. +2. `/.prime/agent/mcp.json` — project, Prime-specific. +3. `~/.prime/agent/mcp.json` — global, applies to every project. + +All existing files are merged. Lower-precedence files are applied first, so a +higher-precedence file overrides a server with the same name. `directTools` are +unioned across files; `idleTimeoutMs` from the highest-precedence file that sets +it wins. A file that cannot be read or parsed is skipped with a warning (shown +in `/mcp status`) rather than disabling the others. + +A `directTools` entry is only honored when the config file that declared it is +also the one that won the referenced server's definition. This prevents a +lower-trust file (a repo `.mcp.json`) from redefining a server name that a +higher-trust file (`~/.prime/agent/mcp.json`) opted to auto-promote, which would +otherwise spawn an unexpected command at startup. Define a server and its +`directTools` in the same file. + +Config is read **once**, from the working directory of the first session in the +process. Promoted `directTools` register as global tools and cannot be +unregistered, so applying config changes (new servers, changed `directTools`) +requires restarting Prime Agent. + +### Keys + +- `mcpServers` — map of server name to stdio or http config. +- `directTools` — array of `"server/tool"` references to promote to first-class + tools. Unknown servers or tools are logged and skipped. +- `idleTimeoutMs` — disconnect a server after this many ms of inactivity + (default `300000`). Set to `0` to keep connections open. + +`${VAR}` references in HTTP `headers` values and stdio `env` values are expanded +from the environment when the server is started, so you can keep secrets out of +committed config files (a missing variable expands to an empty string). + +## Connection lifecycle + +- **Lazy connect.** A server is only started on first use (`list_tools`, + `describe`, `call`, or a `directTools` promotion at startup). +- **Idle disconnect.** Connections close after `idleTimeoutMs` of inactivity and + reconnect transparently on next use. +- **Reconnect on failure.** If an operation fails on a dead transport, the + extension drops the connection and retries once before surfacing the error. +- **Shutdown.** All connections close on `session_shutdown`. HTTP sessions are + terminated server-side on a best-effort basis with a short timeout, so a + server that doesn't support explicit termination — or stops responding to it — + can't stall shutdown; the client is closed regardless. + +Tool result content is passed through in order: text and images (including +images embedded in `resource` blocks) reach the model as text and image content. +`resource_link` blocks and non-image embedded resources are rendered as text +summaries (uri, name, and any inline text), not as separate attachments. + +## The `/mcp` command + +| Command | What it does | +| ------------------------ | --------------------------------------------------- | +| `/mcp status` | Show each server's connection state and tool count. | +| `/mcp tools ` | List a server's tools (connects if needed). | +| `/mcp reconnect [server]`| Reconnect one server, or all if none is given. | +| `/mcp setup` | Print config file locations and an example. | + +## Security + +MCP servers run with your permissions: stdio servers spawn local processes, +HTTP servers receive whatever you put in `headers`. Only configure servers you +trust, and prefer environment-variable references over hard-coded secrets in +committed `.mcp.json` files. + +In the prime-swarm model, MCP is agent-to-tool: the tool implementation ships in +the agent image and only tool *names* cross the swarm wire. Which MCP servers an +agent reaches is governed by the swarm's `egress` and `credentials` controls, not +by any interconnect machinery. See prime-swarm `docs/interconnect.md`. diff --git a/packages/coding-agent/extensions/prime-mcp/config.ts b/packages/coding-agent/extensions/prime-mcp/config.ts new file mode 100644 index 0000000000..a23cab5385 --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/config.ts @@ -0,0 +1,281 @@ +/** + * Configuration loading for the Prime Agent MCP extension. + * + * Servers are declared in `mcp.json` style files using the same `mcpServers` + * shape as other MCP clients, plus two Prime-specific keys: `directTools` and + * `idleTimeoutMs`. Files are merged with project config overriding global + * config. See docs/mcp.md for the precedence rules. + */ + +import { readFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +export interface StdioServerConfig { + type?: "stdio"; + /** Executable to spawn. */ + command: string; + args?: string[]; + env?: Record; + cwd?: string; +} + +export interface HttpServerConfig { + type?: "http"; + /** Streamable HTTP endpoint of the MCP server. */ + url: string; + headers?: Record; +} + +export type McpServerConfig = StdioServerConfig | HttpServerConfig; + +export interface McpConfig { + mcpServers: Record; + /** + * Tools to promote to first-class tools, as `server/tool` references. + * These are registered with their full input schema instead of being + * reachable only through the `mcp` proxy tool. + */ + directTools: string[]; + /** Disconnect an idle server after this many ms. 0 disables idle disconnect. */ + idleTimeoutMs?: number; +} + +export interface LoadedMcpConfig { + config: McpConfig; + /** Files that contributed to the merged config, highest precedence first. */ + sources: string[]; + /** Non-fatal problems (unreadable files, dropped directTools, etc.). */ + warnings: string[]; +} + +export function isHttpServer(config: McpServerConfig): config is HttpServerConfig { + return "url" in config && typeof config.url === "string"; +} + +/** + * Candidate config file paths, highest precedence first. + * + * 1. `/.mcp.json` (project, shared convention) + * 2. `/.prime/agent/mcp.json` (project, Prime-specific) + * 3. `~/.prime/agent/mcp.json` (global) + */ +export function configCandidatePaths(cwd: string, home: string = homedir()): string[] { + return [join(cwd, ".mcp.json"), join(cwd, ".prime", "agent", "mcp.json"), join(home, ".prime", "agent", "mcp.json")]; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Validate that a config value is a string map (e.g. `headers`, `env`). Values + * must be strings so `${VAR}` expansion at connect time never hits a non-string. + */ +function parseStringRecord( + value: unknown, + name: string, + field: string, + source: string, +): Record | undefined { + if (value === undefined) return undefined; + if (!isRecord(value)) { + throw new Error(`Invalid MCP config in ${source}: server "${name}" ${field} must be an object`); + } + for (const [key, entry] of Object.entries(value)) { + if (typeof entry !== "string") { + throw new Error(`Invalid MCP config in ${source}: server "${name}" ${field}.${key} must be a string`); + } + } + return value as Record; +} + +function parseServer(name: string, raw: unknown, source: string): McpServerConfig { + if (!isRecord(raw)) { + throw new Error(`Invalid MCP config in ${source}: server "${name}" must be an object`); + } + + if (typeof raw.url === "string" && typeof raw.command === "string") { + throw new Error( + `Invalid MCP config in ${source}: server "${name}" defines both "command" (stdio) and "url" (http); use one transport`, + ); + } + + if (typeof raw.url === "string") { + const headers = parseStringRecord(raw.headers, name, "headers", source); + return { type: "http", url: raw.url, headers }; + } + + if (typeof raw.command === "string") { + const args = raw.args; + if (args !== undefined && (!Array.isArray(args) || args.some((arg) => typeof arg !== "string"))) { + throw new Error(`Invalid MCP config in ${source}: server "${name}" args must be an array of strings`); + } + const env = parseStringRecord(raw.env, name, "env", source); + if (raw.cwd !== undefined && typeof raw.cwd !== "string") { + throw new Error(`Invalid MCP config in ${source}: server "${name}" cwd must be a string`); + } + return { + type: "stdio", + command: raw.command, + args: args as string[] | undefined, + env, + cwd: raw.cwd, + }; + } + + throw new Error( + `Invalid MCP config in ${source}: server "${name}" must define either "command" (stdio) or "url" (http)`, + ); +} + +interface ParsedFile { + mcpServers: Record; + directTools: string[]; + idleTimeoutMs?: number; +} + +function parseConfigFile(text: string, source: string): ParsedFile { + let json: unknown; + try { + json = JSON.parse(text); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw new Error(`Invalid JSON in MCP config ${source}: ${message}`); + } + + if (!isRecord(json)) { + throw new Error(`Invalid MCP config in ${source}: top level must be an object`); + } + + const servers: Record = {}; + const rawServers = json.mcpServers; + if (rawServers !== undefined) { + if (!isRecord(rawServers)) { + throw new Error(`Invalid MCP config in ${source}: "mcpServers" must be an object`); + } + for (const [name, raw] of Object.entries(rawServers)) { + if (name === "__proto__" || name === "constructor" || name === "prototype") { + throw new Error(`Invalid MCP config in ${source}: server name "${name}" is reserved`); + } + servers[name] = parseServer(name, raw, source); + } + } + + const directTools: string[] = []; + const rawDirect = json.directTools; + if (rawDirect !== undefined) { + if (!Array.isArray(rawDirect) || rawDirect.some((entry) => typeof entry !== "string")) { + throw new Error(`Invalid MCP config in ${source}: "directTools" must be an array of "server/tool" strings`); + } + directTools.push(...(rawDirect as string[])); + } + + let idleTimeoutMs: number | undefined; + const rawIdle = json.idleTimeoutMs; + if (rawIdle !== undefined) { + if (typeof rawIdle !== "number" || !Number.isFinite(rawIdle) || rawIdle < 0) { + throw new Error(`Invalid MCP config in ${source}: "idleTimeoutMs" must be a non-negative number`); + } + idleTimeoutMs = rawIdle; + } + + return { mcpServers: servers, directTools, idleTimeoutMs }; +} + +async function readConfigFile(path: string): Promise { + let text: string; + try { + text = await readFile(path, "utf8"); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + // Treat "not found" and "a path component isn't a directory" as absent so + // an unrelated layout (e.g. a file where `.prime/` is expected) doesn't + // disable every other config file. + if (code === "ENOENT" || code === "ENOTDIR") { + return undefined; + } + throw error; + } + return parseConfigFile(text, path); +} + +/** + * Load and merge MCP config from all candidate paths. + * + * Lower-precedence files are applied first, so higher-precedence files override + * servers with the same name. `directTools` are unioned and `idleTimeoutMs` from + * the highest-precedence file that sets it takes effect. + * + * A file that cannot be read or parsed is skipped with a warning rather than + * failing the whole load, so one bad file never disables every other config. + * + * A `directTools` entry is only honored when the config file that declared it is + * the same one that won the referenced server's definition. This stops a + * lower-trust file (e.g. a repo `.mcp.json`) from redefining a server name that + * a higher-trust file (e.g. `~/.prime/agent/mcp.json`) opted to auto-promote, + * which would otherwise spawn an attacker-controlled command at startup. + */ +export async function loadMcpConfig(cwd: string, home: string = homedir()): Promise { + const paths = configCandidatePaths(cwd, home); + const merged: McpConfig = { mcpServers: {}, directTools: [] }; + const sources: string[] = []; + const warnings: string[] = []; + + const serverSource = new Map(); + const directToolSources = new Map>(); + let idleTimeoutMs: number | undefined; + + // Apply from lowest to highest precedence so later overlays win. + for (const path of [...paths].reverse()) { + let parsed: ParsedFile | undefined; + try { + parsed = await readConfigFile(path); + } catch (error) { + warnings.push(error instanceof Error ? error.message : String(error)); + continue; + } + if (!parsed) continue; + sources.unshift(path); + + for (const [name, server] of Object.entries(parsed.mcpServers)) { + merged.mcpServers[name] = server; + serverSource.set(name, path); + } + for (const ref of parsed.directTools) { + let set = directToolSources.get(ref); + if (!set) { + set = new Set(); + directToolSources.set(ref, set); + } + set.add(path); + } + if (parsed.idleTimeoutMs !== undefined) idleTimeoutMs = parsed.idleTimeoutMs; + } + + if (idleTimeoutMs !== undefined) merged.idleTimeoutMs = idleTimeoutMs; + + for (const [ref, declaredIn] of directToolSources) { + const parsedRef = parseToolRef(ref); + // Keep malformed refs and refs to unknown servers; both are reported with a + // clearer message later by registerDirectTools. + const winner = parsedRef ? serverSource.get(parsedRef.server) : undefined; + if (parsedRef && winner !== undefined && !declaredIn.has(winner)) { + warnings.push( + `Ignoring directTools entry "${ref}": server "${parsedRef.server}" is defined by ${winner}, ` + + `which did not opt into promoting it`, + ); + continue; + } + merged.directTools.push(ref); + } + + return { config: merged, sources, warnings }; +} + +/** Split a `server/tool` reference. Tool names may contain slashes. */ +export function parseToolRef(ref: string): { server: string; tool: string } | undefined { + const slash = ref.indexOf("/"); + if (slash <= 0 || slash === ref.length - 1) return undefined; + return { server: ref.slice(0, slash), tool: ref.slice(slash + 1) }; +} diff --git a/packages/coding-agent/extensions/prime-mcp/connector.ts b/packages/coding-agent/extensions/prime-mcp/connector.ts new file mode 100644 index 0000000000..5def0547bd --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/connector.ts @@ -0,0 +1,162 @@ +/** + * Default connector that wires the manager to real MCP servers via the + * `@modelcontextprotocol/sdk` client and its stdio / streamable-HTTP transports. + */ + +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { isHttpServer, type McpServerConfig } from "./config.js"; +import type { McpCallResult, McpClientLike, McpConnector, McpToolInfo } from "./manager.js"; + +const CLIENT_INFO = { name: "prime-agent-mcp", version: "0.2.2" } as const; +const DEFAULT_CONNECT_TIMEOUT_MS = 30_000; +const DEFAULT_REQUEST_TIMEOUT_MS = 60_000; +// A server that accepts the session DELETE but never answers must not be able +// to wedge shutdown, which awaits disconnectAll(). +const TERMINATE_SESSION_TIMEOUT_MS = 5_000; + +/** Expand `${VAR}` references in a string from the current environment. Missing vars become "". */ +function expandEnv(value: string): string { + return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, name: string) => process.env[name] ?? ""); +} + +function expandRecord(record: Record | undefined): Record | undefined { + if (!record) return undefined; + const out: Record = {}; + for (const [key, value] of Object.entries(record)) out[key] = expandEnv(value); + return out; +} + +function buildTransport(config: McpServerConfig) { + if (isHttpServer(config)) { + const headers = expandRecord(config.headers); + return new StreamableHTTPClientTransport(new URL(config.url), { + requestInit: headers ? { headers } : undefined, + }); + } + return new StdioClientTransport({ + command: config.command, + args: config.args, + // Start from the SDK's safe default env (PATH, HOME, ...) rather than the + // full parent environment, then overlay only the config-provided vars. + env: { ...getDefaultEnvironment(), ...expandRecord(config.env) }, + cwd: config.cwd, + stderr: "ignore", + }); +} + +function withTimeout(promise: Promise, ms: number, label: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); + timer.unref?.(); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (error) => { + clearTimeout(timer); + reject(error); + }, + ); + }); +} + +async function terminateHttpSession(name: string, transport: StreamableHTTPClientTransport): Promise { + try { + await withTimeout( + transport.terminateSession(), + TERMINATE_SESSION_TIMEOUT_MS, + `Terminating MCP session for "${name}"`, + ); + } catch { + // Server may not support explicit termination, may error, or may stall + // past the timeout. In every case we still close the client below. + } +} + +export function adaptClient(client: Client, name: string, transport?: StreamableHTTPClientTransport): McpClientLike { + return { + async listTools(signal) { + const tools: McpToolInfo[] = []; + let cursor: string | undefined; + do { + const page = await client.listTools({ cursor }, { signal, timeout: DEFAULT_REQUEST_TIMEOUT_MS }); + for (const tool of page.tools) { + tools.push({ + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema as Record, + }); + } + cursor = page.nextCursor as string | undefined; + } while (cursor); + return tools; + }, + async callTool(tool, args, signal): Promise { + const result = (await client.callTool({ name: tool, arguments: args }, undefined, { + signal, + timeout: DEFAULT_REQUEST_TIMEOUT_MS, + })) as { + content?: unknown; + toolResult?: unknown; + isError?: boolean; + structuredContent?: unknown; + }; + return { + content: result.content ?? result.toolResult, + isError: result.isError === true, + structuredContent: result.structuredContent, + }; + }, + async close() { + // End the server-side session for HTTP transports so idle disconnects + // and shutdown don't accumulate abandoned sessions on the remote, but + // always close the client even if termination stalls or fails. + try { + if (transport) await terminateHttpSession(name, transport); + } finally { + await client.close(); + } + }, + }; +} + +export interface ConnectorOptions { + connectTimeoutMs?: number; +} + +export function createDefaultConnector(options: ConnectorOptions = {}): McpConnector { + const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS; + return async (name, config, signal) => { + const client = new Client(CLIENT_INFO); + const transport = buildTransport(config); + // Abort the underlying connect on timeout (or caller abort) so the SDK + // actually cancels the in-flight request, rather than leaving an orphaned + // connect that can still open a server-side HTTP session after we bail. + const controller = new AbortController(); + const onCallerAbort = () => controller.abort(); + if (signal) { + if (signal.aborted) controller.abort(); + else signal.addEventListener("abort", onCallerAbort, { once: true }); + } + const timer = setTimeout(() => controller.abort(), connectTimeoutMs); + timer.unref?.(); + try { + await client.connect(transport, { signal: controller.signal }); + } catch (error) { + // A stalled connect may already hold a server-side HTTP session; end it + // (bounded) so timed-out connects don't leak sessions on the remote. + if (transport instanceof StreamableHTTPClientTransport) { + await terminateHttpSession(name, transport); + } + await client.close().catch(() => {}); + throw error; + } finally { + clearTimeout(timer); + signal?.removeEventListener("abort", onCallerAbort); + } + return adaptClient(client, name, transport instanceof StreamableHTTPClientTransport ? transport : undefined); + }; +} diff --git a/packages/coding-agent/extensions/prime-mcp/content.ts b/packages/coding-agent/extensions/prime-mcp/content.ts new file mode 100644 index 0000000000..564c762ac0 --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/content.ts @@ -0,0 +1,144 @@ +/** + * Render MCP tool call results into Prime Agent tool content. + * + * MCP results carry an array of typed content blocks (text, image, audio, + * resource links, embedded resources) plus optional `structuredContent`. The + * proxy tool and promoted direct tools share this so non-text payloads (notably + * images) reach the model instead of being flattened to a placeholder. Block + * order is preserved so captions stay attached to the right image. + */ + +import type { ImageContent, TextContent } from "@earendil-works/pi-ai"; + +const MAX_TEXT_CHARS = 20_000; + +export type ToolContent = TextContent | ImageContent; + +export interface RenderedCall { + /** Full content (text + images) for an AgentToolResult, in original order. */ + content: ToolContent[]; + /** Plain-text summary, used for error messages. */ + text: string; +} + +interface EmbeddedResource { + uri?: string; + text?: string; + blob?: string; + mimeType?: string; + name?: string; +} + +interface McpBlock { + type?: string; + text?: string; + data?: string; + mimeType?: string; + uri?: string; + name?: string; + description?: string; + resource?: EmbeddedResource; +} + +function truncate(text: string): string { + if (text.length <= MAX_TEXT_CHARS) return text; + return `${text.slice(0, MAX_TEXT_CHARS)}\n\n[Output truncated: ${text.length} chars total. Call the tool with narrower arguments for less output.]`; +} + +function normalizeBlocks(content: unknown): Array { + if (content == null) return []; + if (typeof content === "string") return [{ type: "text", text: content }]; + if (Array.isArray(content)) return content as Array; + return [{ type: "_json" }]; +} + +function isImageMime(mimeType: string | undefined): mimeType is string { + return typeof mimeType === "string" && mimeType.startsWith("image/"); +} + +function resourceLinkLine(block: McpBlock): string { + const suffix = block.description ? ` — ${block.description}` : ""; + if (block.name && block.uri) return `[resource_link] ${block.name}: ${block.uri}${suffix}`; + const label = block.name ?? block.uri ?? "resource"; + return `[resource_link] ${label}${suffix}`; +} + +function embeddedResourceLine(resource: EmbeddedResource): string { + if (resource.name && resource.uri) return `[resource] ${resource.name}: ${resource.uri}`; + const label = resource.name ?? resource.uri; + return label ? `[resource] ${label}` : "[resource]"; +} + +/** Convert an MCP content array (with structuredContent fallback) to tool content. */ +export function renderMcpCall(content: unknown, structuredContent?: unknown): RenderedCall { + const out: ToolContent[] = []; + const textSummary: string[] = []; + let buffer: string[] = []; + + const flush = (): void => { + if (buffer.length === 0) return; + out.push({ type: "text", text: truncate(buffer.join("\n")) }); + buffer = []; + }; + const pushText = (text: string): void => { + buffer.push(text); + textSummary.push(text); + }; + const pushImage = (data: string, mimeType: string): void => { + flush(); + out.push({ type: "image", data, mimeType }); + }; + + for (const block of normalizeBlocks(content)) { + if (block == null) continue; + switch (block.type) { + case "text": + if (typeof block.text === "string") pushText(block.text); + break; + case "image": + if (typeof block.data === "string" && typeof block.mimeType === "string") { + pushImage(block.data, block.mimeType); + } else { + pushText("[image content]"); + } + break; + case "audio": + pushText(block.mimeType ? `[audio content: ${block.mimeType}]` : "[audio content]"); + break; + case "resource_link": + pushText(resourceLinkLine(block)); + break; + case "resource": { + const resource = block.resource; + if (resource?.blob && isImageMime(resource.mimeType)) { + pushImage(resource.blob, resource.mimeType); + } else if (typeof resource?.text === "string") { + pushText(resource.text); + } else if (resource) { + pushText(embeddedResourceLine(resource)); + } else { + pushText("[resource]"); + } + break; + } + case "_json": + pushText(JSON.stringify(content, null, 2)); + break; + default: + pushText(JSON.stringify(block)); + } + } + flush(); + + let text = textSummary.join("\n"); + if (out.length === 0 && structuredContent !== undefined) { + text = JSON.stringify(structuredContent, null, 2); + out.push({ type: "text", text: truncate(text) }); + } + if (out.length === 0) out.push({ type: "text", text: "(empty result)" }); + + // `text` feeds thrown error messages, which the agent loop turns into tool + // result content verbatim; bound it so a huge error payload can't blow past + // the output cap the content blocks already respect. + return { content: out, text: truncate(text) }; +} diff --git a/packages/coding-agent/extensions/prime-mcp/direct-tools.ts b/packages/coding-agent/extensions/prime-mcp/direct-tools.ts new file mode 100644 index 0000000000..419d27ca06 --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/direct-tools.ts @@ -0,0 +1,135 @@ +/** + * Promotes selected MCP tools to first-class Prime Agent tools. + * + * Most tools stay behind the `mcp` proxy to keep the prompt small, but a few + * hot tools can be listed in `directTools` so the model sees their real schema + * and can call them directly. pi validates tool arguments against raw JSON + * Schema, so an MCP tool's `inputSchema` is used as the tool parameters as-is. + */ + +import { createHash } from "node:crypto"; +import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { type TSchema, Type } from "typebox"; +import { parseToolRef } from "./config.js"; +import { renderMcpCall } from "./content.js"; +import { isMcpConnectionError, type McpManager, type McpToolInfo } from "./manager.js"; + +// OpenAI-compatible providers cap tool names at 64 characters; exceed it and the +// whole request is rejected, not just the offending tool. +const MAX_TOOL_NAME = 64; + +export interface DirectToolRegistration { + ref: string; + status: "deferred" | "resolved"; +} + +/** + * Build a valid tool name like `mcp__server__tool`. Characters outside + * `[A-Za-z0-9_]` are replaced, so distinct refs can in theory collide; + * `registerDirectTools` detects and warns about that. Names longer than the + * provider limit are truncated with a short hash of the original ref appended, + * keeping them unique and stable. + */ +export function directToolName(server: string, tool: string): string { + const clean = (value: string) => value.replace(/[^a-zA-Z0-9_]/g, "_"); + const name = `mcp__${clean(server)}__${clean(tool)}`; + if (name.length <= MAX_TOOL_NAME) return name; + const hash = createHash("sha1").update(`${server}\u0000${tool}`).digest("hex").slice(0, 8); + return `${name.slice(0, MAX_TOOL_NAME - hash.length - 1)}_${hash}`; +} + +export function buildDirectTool(manager: McpManager, server: string, info: McpToolInfo): ToolDefinition { + return { + name: directToolName(server, info.name), + label: `${server}/${info.name}`, + description: info.description ? `[MCP ${server}] ${info.description}` : `[MCP ${server}] Tool "${info.name}"`, + parameters: info.inputSchema as unknown as TSchema, + async execute(_toolCallId, params, signal) { + const args = (params ?? {}) as Record; + const call = await manager.callTool(server, info.name, args, signal); + const rendered = renderMcpCall(call.content, call.structuredContent); + if (call.isError) { + throw new Error(rendered.text || `MCP tool ${server}/${info.name} returned an error`); + } + return { + content: rendered.content, + details: { server, tool: info.name }, + }; + }, + }; +} + +function buildDeferredDirectTool(manager: McpManager, server: string, tool: string): ToolDefinition { + return { + name: directToolName(server, tool), + label: `${server}/${tool}`, + description: `[MCP ${server}] Tool "${tool}" (schema unavailable until the server reconnects)`, + parameters: Type.Record(Type.String(), Type.Unknown()), + async execute(_toolCallId, params, signal) { + const args = (params ?? {}) as Record; + const call = await manager.callTool(server, tool, args, signal); + const rendered = renderMcpCall(call.content, call.structuredContent); + if (call.isError) { + throw new Error(rendered.text || `MCP tool ${server}/${tool} returned an error`); + } + return { + content: rendered.content, + details: { server, tool }, + }; + }, + }; +} + +/** + * Resolve and register every `directTools` reference. Failures are logged and + * skipped so a single bad server never blocks the rest of the extension. + */ +export async function registerDirectTools( + pi: ExtensionAPI, + manager: McpManager, + refs: string[], + logger: (message: string) => void, + registered: Map = new Map(), + signal?: AbortSignal, +): Promise { + // `refs` arrives lowest-precedence first. Process highest first so that when + // two distinct refs sanitize to the same tool name, the higher-precedence + // (e.g. project) one wins and the lower-precedence one is the skipped collision. + for (const ref of [...refs].reverse()) { + const parsed = parseToolRef(ref); + if (!parsed) { + logger(`Ignoring malformed directTools entry "${ref}" (expected "server/tool")`); + continue; + } + if (!manager.hasServer(parsed.server)) { + logger(`directTools entry "${ref}" references unknown server "${parsed.server}"`); + continue; + } + + const name = directToolName(parsed.server, parsed.tool); + const owner = registered.get(name); + if (owner !== undefined && owner.ref !== ref) { + logger(`directTools entry "${ref}" collides with "${owner.ref}" as tool "${name}"; skipping`); + continue; + } + if (owner?.status === "resolved") continue; + + try { + const info = await manager.describeTool(parsed.server, parsed.tool, signal); + registered.set(name, { ref, status: "resolved" }); + pi.registerTool(buildDirectTool(manager, parsed.server, info)); + } catch (error) { + if (isMcpConnectionError(error)) { + if (owner?.status !== "deferred") { + registered.set(name, { ref, status: "deferred" }); + pi.registerTool(buildDeferredDirectTool(manager, parsed.server, parsed.tool)); + } + const message = error instanceof Error ? error.message : String(error); + logger(`Registered directTools entry "${ref}" with deferred schema: ${message}`); + continue; + } + const message = error instanceof Error ? error.message : String(error); + logger(`Could not promote directTools entry "${ref}": ${message}`); + } + } +} diff --git a/packages/coding-agent/extensions/prime-mcp/index.ts b/packages/coding-agent/extensions/prime-mcp/index.ts new file mode 100644 index 0000000000..7accad41dc --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/index.ts @@ -0,0 +1,184 @@ +/** + * Prime Agent MCP extension. + * + * Registers a single `mcp` proxy tool plus optional first-class `directTools`, + * manages lazy connections to configured MCP servers, and adds a `/mcp` command + * for status, tools, reconnect, and setup. See docs/mcp.md. + */ + +import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent"; +import { configCandidatePaths, loadMcpConfig } from "./config.js"; +import { createDefaultConnector } from "./connector.js"; +import { type DirectToolRegistration, registerDirectTools } from "./direct-tools.js"; +import { McpManager } from "./manager.js"; +import { createMcpProxyTool } from "./proxy-tool.js"; + +function notify(ctx: ExtensionCommandContext, message: string, level: "info" | "warning" | "error" = "info"): void { + if (ctx.hasUI) ctx.ui.notify(message, level); +} + +export default function primeMcpExtension(pi: ExtensionAPI): void { + // Persistent problems from loading config / promoting tools. Live connection + // errors are not kept here; `/mcp status` reads those from the manager so they + // reflect the current state instead of going stale. + let configWarnings: string[] = []; + let directToolRefs: string[] = []; + const promoted = new Map(); + let loadPromise: Promise | undefined; + + const manager = new McpManager({ mcpServers: {}, directTools: [] }, { connector: createDefaultConnector() }); + + pi.registerTool(createMcpProxyTool(manager)); + + const doLoad = async (cwd: string): Promise => { + configWarnings = []; + const loaded = await loadMcpConfig(cwd); + configWarnings.push(...loaded.warnings); + directToolRefs = loaded.config.directTools; + await manager.setConfig(loaded.config); + if (directToolRefs.length > 0) { + await registerDirectTools(pi, manager, directToolRefs, (m) => configWarnings.push(m), promoted); + } + }; + + // Config (servers and promoted directTools) is resolved once, from the first + // session's working directory. Promoted tools register globally and cannot be + // unregistered, so reloading per session would risk leaving direct tools that + // point at servers a later config removed. Restart to apply config changes. + // Concurrent session starts share one load; a failed load is retried later. + const loadOnce = (cwd: string): Promise => { + if (!loadPromise) { + loadPromise = doLoad(cwd).catch((error) => { + configWarnings.push(error instanceof Error ? error.message : String(error)); + loadPromise = undefined; + }); + } + return loadPromise; + }; + + pi.on("session_start", async (_event, ctx) => { + await loadOnce(ctx.cwd); + if (configWarnings.length > 0 && ctx.hasUI) { + ctx.ui.notify(`MCP: ${configWarnings.join("; ")}`, "warning"); + } + }); + + pi.on("session_shutdown", async () => { + await manager.disconnectAll(); + }); + + pi.registerCommand("mcp", { + description: "Manage MCP servers: status, tools [server], reconnect [server], setup", + getArgumentCompletions: (prefix: string) => { + const subcommands = ["status", "tools", "reconnect", "setup"]; + const items = subcommands.filter((s) => s.startsWith(prefix)).map((s) => ({ value: s, label: s })); + return items.length > 0 ? items : null; + }, + handler: async (args, ctx) => { + const [subcommand, target] = args.trim().split(/\s+/).filter(Boolean); + + switch (subcommand ?? "status") { + case "status": { + const statuses = manager.listStatuses(); + if (statuses.length === 0) { + const base = "No MCP servers configured. Run /mcp setup."; + const message = configWarnings.length > 0 ? `${base}\nwarnings: ${configWarnings.join("; ")}` : base; + notify(ctx, message, configWarnings.length > 0 ? "warning" : "info"); + return; + } + const lines = statuses.map( + (status) => + `${status.name}: ${status.state} (${status.transport})${ + status.toolCount !== undefined ? `, ${status.toolCount} tools` : "" + }${status.error ? ` — ${status.error}` : ""}`, + ); + if (configWarnings.length > 0) lines.push(`warnings: ${configWarnings.join("; ")}`); + notify(ctx, lines.join("\n"), "info"); + return; + } + + case "tools": { + if (!target) { + notify(ctx, "Usage: /mcp tools ", "warning"); + return; + } + if (!manager.hasServer(target)) { + notify(ctx, `Unknown MCP server: ${target}`, "error"); + return; + } + try { + const tools = await manager.listTools(target, ctx.signal); + const lines = tools.map( + (tool) => `- ${tool.name}${tool.description ? `: ${tool.description.split("\n")[0]}` : ""}`, + ); + notify( + ctx, + lines.length > 0 ? `Tools on ${target}:\n${lines.join("\n")}` : `${target} exposes no tools.`, + "info", + ); + } catch (error) { + notify( + ctx, + `Failed to list tools for ${target}: ${error instanceof Error ? error.message : String(error)}`, + "error", + ); + } + return; + } + + case "reconnect": { + const targets = target ? [target] : manager.serverNames(); + if (target && !manager.hasServer(target)) { + notify(ctx, `Unknown MCP server: ${target}`, "error"); + return; + } + if (targets.length === 0) { + notify(ctx, "No MCP servers configured.", "info"); + return; + } + const reconnected: string[] = []; + const failed: string[] = []; + for (const name of targets) { + try { + await manager.reconnect(name, ctx.signal); + if (directToolRefs.length > 0) { + await registerDirectTools( + pi, + manager, + directToolRefs, + (message) => failed.push(message), + promoted, + ctx.signal, + ); + } + reconnected.push(name); + } catch (error) { + failed.push(`${name} (${error instanceof Error ? error.message : String(error)})`); + } + } + const parts: string[] = []; + if (reconnected.length > 0) parts.push(`Reconnected: ${reconnected.join(", ")}`); + if (failed.length > 0) parts.push(`Failed: ${failed.join(", ")}`); + notify(ctx, parts.join("\n"), failed.length > 0 ? "error" : "info"); + return; + } + + case "setup": { + const paths = configCandidatePaths(ctx.cwd); + const lines = [ + "MCP config is read from (highest precedence first):", + ...paths.map((path, index) => ` ${index + 1}. ${path}`), + "", + "Example mcp.json:", + '{ "mcpServers": { "example": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-everything"] } } }', + ]; + notify(ctx, lines.join("\n"), "info"); + return; + } + + default: + notify(ctx, `Unknown subcommand "${subcommand}". Use status, tools, reconnect, or setup.`, "warning"); + } + }, + }); +} diff --git a/packages/coding-agent/extensions/prime-mcp/manager.ts b/packages/coding-agent/extensions/prime-mcp/manager.ts new file mode 100644 index 0000000000..04d126b45a --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/manager.ts @@ -0,0 +1,375 @@ +/** + * Connection manager for configured MCP servers. + * + * Connections are established lazily on first use, cached, torn down after an + * idle period, and transparently re-established once if an idempotent metadata + * read fails on a dead transport. The actual transport wiring lives in + * `connector.ts` and is injectable so tests can run against an in-memory server. + */ + +import { isHttpServer, type McpConfig, type McpServerConfig } from "./config.js"; + +export interface McpToolInfo { + name: string; + description?: string; + inputSchema: Record; +} + +export interface McpCallResult { + content: unknown; + isError: boolean; + /** MCP allows any JSON value here, including scalars. */ + structuredContent?: unknown; +} + +/** Minimal client surface the manager depends on. */ +export interface McpClientLike { + listTools(signal?: AbortSignal): Promise; + callTool(tool: string, args: Record | undefined, signal?: AbortSignal): Promise; + close(): Promise; +} + +export type McpConnector = (name: string, config: McpServerConfig, signal?: AbortSignal) => Promise; + +export type ServerState = "disconnected" | "connected" | "error"; + +export interface ServerStatus { + name: string; + transport: "stdio" | "http"; + state: ServerState; + toolCount?: number; + error?: string; +} + +const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000; + +interface Connection { + client: McpClientLike; + tools?: McpToolInfo[]; + idleTimer?: ReturnType; + /** Number of operations currently running against this connection. */ + active: number; + /** Evicted from the map; close once the last in-flight operation drains. */ + doomed?: boolean; + /** Guards against closing the same client twice. */ + closed?: boolean; +} + +interface ManagerOptions { + connector: McpConnector; + idleTimeoutMs?: number; + logger?: (message: string) => void; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function isAbort(error: unknown): boolean { + return error instanceof Error && (error.name === "AbortError" || error.message.includes("aborted")); +} + +const CONNECTION_ERROR = + /\b(not connected|connection (closed|reset|refused|lost)|transport (closed|error)|socket hang up|econnreset|econnrefused|epipe|premature close|stream is not readable|terminated|timed out|timeout)\b/i; + +/** + * Whether an error looks like a dead transport rather than a tool-level failure. + * Only these are retried, so a stateful tool that errored after doing work is + * never silently re-invoked. + */ +export function isMcpConnectionError(error: unknown): boolean { + return error instanceof Error && CONNECTION_ERROR.test(error.message); +} + +export class McpManager { + private readonly connections = new Map(); + private readonly connecting = new Map; controller: AbortController }>(); + private readonly states = new Map(); + private config: McpConfig; + private idleTimeoutMs: number; + + constructor( + config: McpConfig, + private readonly options: ManagerOptions, + ) { + this.config = config; + this.idleTimeoutMs = options.idleTimeoutMs ?? config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS; + } + + /** Replace the server configuration, dropping any existing connections. */ + async setConfig(config: McpConfig): Promise { + await this.disconnectAll(); + this.config = config; + this.idleTimeoutMs = this.options.idleTimeoutMs ?? config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS; + } + + serverNames(): string[] { + return Object.keys(this.config.mcpServers); + } + + hasServer(name: string): boolean { + // Own-property check only: `"toString" in {}` is true, which would + // otherwise treat inherited Object members as configured servers. + return Object.hasOwn(this.config.mcpServers, name); + } + + getStatus(name: string): ServerStatus | undefined { + const serverConfig = this.config.mcpServers[name]; + if (!serverConfig) return undefined; + const tracked = this.states.get(name); + return { + name, + transport: isHttpServer(serverConfig) ? "http" : "stdio", + state: tracked?.state ?? "disconnected", + toolCount: this.connections.get(name)?.tools?.length, + error: tracked?.error, + }; + } + + listStatuses(): ServerStatus[] { + return this.serverNames().map((name) => this.getStatus(name)!); + } + + private requireServerConfig(name: string): McpServerConfig { + if (!Object.hasOwn(this.config.mcpServers, name)) throw new Error(`Unknown MCP server: "${name}"`); + return this.config.mcpServers[name]; + } + + private clearIdle(name: string): void { + const connection = this.connections.get(name); + if (connection?.idleTimer) { + clearTimeout(connection.idleTimer); + connection.idleTimer = undefined; + } + } + + private scheduleIdleDisconnect(name: string): void { + const connection = this.connections.get(name); + if (!connection) return; + if (connection.idleTimer) clearTimeout(connection.idleTimer); + // An operation is still in flight; it will reschedule when it finishes. + if (connection.active > 0) return; + if (this.idleTimeoutMs <= 0) return; + connection.idleTimer = setTimeout(() => { + void this.disconnect(name); + }, this.idleTimeoutMs); + // Never let an idle MCP connection keep the process alive. + connection.idleTimer.unref?.(); + } + + /** + * Connect to a server, deduping concurrent attempts. The attempt has its own + * AbortController (not any caller's signal) so one caller aborting cannot kill + * a connection others are waiting on, while `disconnect` can still cancel a + * hung connect promptly instead of blocking on the connector's own timeout. + */ + private connect(name: string): Promise { + const existing = this.connecting.get(name); + if (existing) return existing.promise; + + const serverConfig = this.requireServerConfig(name); + const controller = new AbortController(); + const promise = (async (): Promise => { + try { + const client = await this.options.connector(name, serverConfig, controller.signal); + const connection: Connection = { client, active: 0 }; + this.connections.set(name, connection); + this.states.set(name, { state: "connected" }); + return connection; + } catch (error) { + this.states.set(name, { state: "error", error: errorMessage(error) }); + throw error; + } finally { + this.connecting.delete(name); + } + })(); + + this.connecting.set(name, { promise, controller }); + return promise; + } + + /** + * Wait for a (possibly shared) connect, abandoning the wait if the caller + * aborts. The shared connect controller is left untouched so cancelling one + * call never tears down a connection other callers are still waiting on. + */ + private waitForConnect(name: string, signal?: AbortSignal): Promise { + const connectPromise = this.connect(name); + if (!signal) return connectPromise; + if (signal.aborted) return Promise.reject(new DOMException("Aborted", "AbortError")); + return new Promise((resolve, reject) => { + const onAbort = () => reject(new DOMException("Aborted", "AbortError")); + signal.addEventListener("abort", onAbort, { once: true }); + connectPromise.then( + (connection) => { + signal.removeEventListener("abort", onAbort); + resolve(connection); + }, + (error) => { + signal.removeEventListener("abort", onAbort); + reject(error); + }, + ); + }); + } + + /** + * Begin an operation: ensure a live connection and disarm idle disconnect so + * the timer can never close a connection out from under an in-flight call. + */ + private async begin(name: string, signal?: AbortSignal): Promise { + const connection = this.connections.get(name) ?? (await this.waitForConnect(name, signal)); + connection.active += 1; + this.clearIdle(name); + return connection; + } + + /** + * End an operation against a specific connection. Decrement that instance's + * counter (not whatever is current under `name`, which may have been replaced + * by a reconnect). A doomed connection is closed once the last operation + * drains; the live, idle one rearms idle disconnect instead. + */ + private end(name: string, connection: Connection): void { + connection.active = Math.max(0, connection.active - 1); + if (connection.active > 0) return; + if (connection.doomed) { + void this.closeClient(name, connection); + return; + } + if (this.connections.get(name) === connection) { + this.scheduleIdleDisconnect(name); + } + } + + /** + * Run an operation against a connected client, retrying once on a dead + * transport. Only transport-level failures are retried; tool-level errors and + * aborts propagate untouched so a tool that already acted is never re-invoked. + */ + private async withConnection( + name: string, + signal: AbortSignal | undefined, + retryOnConnectionError: boolean, + op: (connection: Connection) => Promise, + ): Promise { + this.requireServerConfig(name); + const connection = await this.begin(name, signal); + let endConnection = true; + try { + try { + return await op(connection); + } catch (error) { + if (!retryOnConnectionError || isAbort(error) || signal?.aborted || !isMcpConnectionError(error)) { + throw error; + } + this.options.logger?.(`MCP server "${name}" operation failed, reconnecting: ${errorMessage(error)}`); + } + // Retire only this dead instance. Sibling calls sharing it keep it + // alive until they drain (see end); we never close it out from under + // them. A fresh begin() reconnects for our retry. + this.evict(name, connection); + this.end(name, connection); + endConnection = false; + let next: Connection | undefined; + try { + next = await this.begin(name, signal); + return await op(next); + } finally { + if (next) this.end(name, next); + } + } finally { + if (endConnection) this.end(name, connection); + } + } + + async listTools(name: string, signal?: AbortSignal): Promise { + return this.withConnection(name, signal, true, async (connection) => { + if (!connection.tools) { + connection.tools = await connection.client.listTools(signal); + } + return connection.tools; + }); + } + + async describeTool(name: string, tool: string, signal?: AbortSignal): Promise { + const tools = await this.listTools(name, signal); + const found = tools.find((t) => t.name === tool); + if (!found) { + throw new Error(`MCP server "${name}" has no tool "${tool}"`); + } + return found; + } + + async callTool( + name: string, + tool: string, + args: Record | undefined, + signal?: AbortSignal, + ): Promise { + return this.withConnection(name, signal, false, (connection) => connection.client.callTool(tool, args, signal)); + } + + async reconnect(name: string, signal?: AbortSignal): Promise { + this.requireServerConfig(name); + await this.disconnect(name); + const connection = await this.begin(name, signal); + this.end(name, connection); + } + + /** + * Mark a connection retired and remove it from the map if it is still the + * current one, without closing it. The actual close is deferred to `end` so + * sibling operations still using this client are never cut off mid-call. + */ + private evict(name: string, connection: Connection): void { + if (this.connections.get(name) === connection) { + this.connections.delete(name); + this.states.set(name, { state: "disconnected" }); + } + connection.doomed = true; + if (connection.idleTimer) { + clearTimeout(connection.idleTimer); + connection.idleTimer = undefined; + } + } + + private async closeClient(name: string, connection: Connection): Promise { + if (connection.closed) return; + connection.closed = true; + if (connection.idleTimer) { + clearTimeout(connection.idleTimer); + connection.idleTimer = undefined; + } + try { + await connection.client.close(); + } catch (error) { + this.options.logger?.(`Error closing MCP server "${name}": ${errorMessage(error)}`); + } + } + + async disconnect(name: string): Promise { + // A connect may still be in flight; abort it (so a hung connector doesn't + // block shutdown) and wait so we never leak a client that resolves after + // we thought the server was gone. + const pending = this.connecting.get(name); + if (pending) { + pending.controller.abort(); + try { + await pending.promise; + } catch { + // Connection failed or was aborted; nothing to close. + } + } + const connection = this.connections.get(name); + if (!connection) return; + this.evict(name, connection); + if (connection.active > 0) return; + await this.closeClient(name, connection); + } + + async disconnectAll(): Promise { + const names = new Set([...this.connections.keys(), ...this.connecting.keys()]); + await Promise.all([...names].map((name) => this.disconnect(name))); + } +} diff --git a/packages/coding-agent/extensions/prime-mcp/mcp.json.example b/packages/coding-agent/extensions/prime-mcp/mcp.json.example new file mode 100644 index 0000000000..33c785f620 --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/mcp.json.example @@ -0,0 +1,23 @@ +{ + "mcpServers": { + "everything": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-everything"] + }, + "filesystem": { + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"], + "env": { + "EXAMPLE_TOKEN": "set-me" + } + }, + "remote": { + "url": "https://example.com/mcp", + "headers": { + "Authorization": "Bearer ${YOUR_TOKEN}" + } + } + }, + "directTools": ["everything/echo"], + "idleTimeoutMs": 300000 +} diff --git a/packages/coding-agent/extensions/prime-mcp/package.json b/packages/coding-agent/extensions/prime-mcp/package.json new file mode 100644 index 0000000000..871dae403e --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/package.json @@ -0,0 +1,25 @@ +{ + "name": "prime-agent-extension-mcp", + "private": true, + "version": "0.2.2", + "type": "module", + "description": "First-party Model Context Protocol (MCP) client for Prime Agent. Calls external MCP servers through a single token-efficient proxy tool.", + "keywords": ["pi-package", "prime-agent", "mcp"], + "scripts": { + "clean": "echo 'nothing to clean'", + "build": "echo 'nothing to build'", + "check": "echo 'nothing to check'" + }, + "pi": { + "extensions": ["./index.ts"] + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.29.0" + }, + "peerDependencies": { + "@earendil-works/pi-ai": "*", + "@earendil-works/pi-coding-agent": "*", + "@earendil-works/pi-tui": "*", + "typebox": "*" + } +} diff --git a/packages/coding-agent/extensions/prime-mcp/proxy-tool.ts b/packages/coding-agent/extensions/prime-mcp/proxy-tool.ts new file mode 100644 index 0000000000..3436b27502 --- /dev/null +++ b/packages/coding-agent/extensions/prime-mcp/proxy-tool.ts @@ -0,0 +1,131 @@ +/** + * The `mcp` proxy tool: a single tool the model uses to discover and call tools + * across every configured MCP server. Keeping one tool in the prompt avoids + * loading every server's full tool schema into context up front. + */ + +import { StringEnum } from "@earendil-works/pi-ai"; +import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; +import { Type } from "typebox"; +import { renderMcpCall } from "./content.js"; +import type { McpManager, McpToolInfo } from "./manager.js"; + +const MAX_RESULT_CHARS = 20_000; + +const McpProxyParams = Type.Object({ + action: StringEnum(["list_servers", "list_tools", "describe", "call"] as const, { + description: + "list_servers: show configured servers; list_tools: list a server's tools; describe: show one tool's input schema; call: invoke a tool", + }), + server: Type.Optional(Type.String({ description: "Server name (required for list_tools, describe, call)" })), + tool: Type.Optional(Type.String({ description: "Tool name (required for describe and call)" })), + arguments: Type.Optional( + Type.Record(Type.String(), Type.Unknown(), { description: "Arguments object passed to the tool (for call)" }), + ), +}); + +export type McpProxyInput = { + action: "list_servers" | "list_tools" | "describe" | "call"; + server?: string; + tool?: string; + arguments?: Record; +}; + +export interface McpProxyDetails { + action: string; + server?: string; + tool?: string; +} + +function truncate(text: string): string { + if (text.length <= MAX_RESULT_CHARS) return text; + return `${text.slice(0, MAX_RESULT_CHARS)}\n\n[Output truncated: ${text.length} chars total. Call the tool with narrower arguments for less output.]`; +} + +function summarizeTool(tool: McpToolInfo): string { + const description = tool.description?.split("\n")[0]?.trim(); + return description ? `${tool.name} — ${description}` : tool.name; +} + +function result(text: string, details: McpProxyDetails) { + return { content: [{ type: "text" as const, text: truncate(text) }], details }; +} + +export function createMcpProxyTool(manager: McpManager): ToolDefinition { + return { + name: "mcp", + label: "MCP", + description: + "Discover and call tools on external MCP (Model Context Protocol) servers. Use action=list_servers to see what is available, list_tools to see a server's tools, describe to read a tool's input schema, and call to invoke a tool. Prefer describe before call so arguments match the schema.", + promptGuidelines: [ + "Use the mcp tool to reach external MCP servers; start with action=list_servers, then list_tools and describe before action=call.", + ], + parameters: McpProxyParams, + async execute(_toolCallId, params, signal) { + switch (params.action) { + case "list_servers": { + const statuses = manager.listStatuses(); + if (statuses.length === 0) { + return result( + "No MCP servers are configured. Add servers to .mcp.json or ~/.prime/agent/mcp.json (see /mcp setup).", + { action: params.action }, + ); + } + const lines = statuses.map( + (status) => + `- ${status.name} (${status.transport}, ${status.state}${ + status.toolCount !== undefined ? `, ${status.toolCount} tools` : "" + })${status.error ? ` — ${status.error}` : ""}`, + ); + return result(`Configured MCP servers:\n${lines.join("\n")}`, { action: params.action }); + } + + case "list_tools": { + if (!params.server) throw new Error("action=list_tools requires a server"); + const tools = await manager.listTools(params.server, signal); + if (tools.length === 0) { + return result(`Server "${params.server}" exposes no tools.`, { + action: params.action, + server: params.server, + }); + } + const lines = tools.map((tool) => `- ${summarizeTool(tool)}`); + return result(`Tools on "${params.server}":\n${lines.join("\n")}`, { + action: params.action, + server: params.server, + }); + } + + case "describe": { + if (!params.server) throw new Error("action=describe requires a server"); + if (!params.tool) throw new Error("action=describe requires a tool"); + const tool = await manager.describeTool(params.server, params.tool, signal); + const text = [ + `${params.server}/${tool.name}`, + tool.description ?? "(no description)", + "", + "Input schema:", + JSON.stringify(tool.inputSchema, null, 2), + ].join("\n"); + return result(text, { action: params.action, server: params.server, tool: params.tool }); + } + + case "call": { + if (!params.server) throw new Error("action=call requires a server"); + if (!params.tool) throw new Error("action=call requires a tool"); + const call = await manager.callTool(params.server, params.tool, params.arguments, signal); + const rendered = renderMcpCall(call.content, call.structuredContent); + // Surface MCP tool errors as tool errors so the agent loop flags them, + // matching how promoted directTools behave. + if (call.isError) { + throw new Error(rendered.text || `MCP tool ${params.server}/${params.tool} returned an error`); + } + return { + content: rendered.content, + details: { action: params.action, server: params.server, tool: params.tool }, + }; + } + } + }, + }; +} diff --git a/packages/coding-agent/test/prime-mcp.test.ts b/packages/coding-agent/test/prime-mcp.test.ts new file mode 100644 index 0000000000..7e921f1aa1 --- /dev/null +++ b/packages/coding-agent/test/prime-mcp.test.ts @@ -0,0 +1,673 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { z } from "zod"; +import { configCandidatePaths, loadMcpConfig, parseToolRef } from "../extensions/prime-mcp/config.js"; +import { adaptClient } from "../extensions/prime-mcp/connector.js"; +import { renderMcpCall } from "../extensions/prime-mcp/content.js"; +import { directToolName, registerDirectTools } from "../extensions/prime-mcp/direct-tools.js"; +import { type McpClientLike, type McpConnector, McpManager } from "../extensions/prime-mcp/manager.js"; +import { createMcpProxyTool, type McpProxyInput } from "../extensions/prime-mcp/proxy-tool.js"; +import type { ExtensionAPI, ToolDefinition } from "../src/core/extensions/types.js"; + +async function callProxy(manager: McpManager, params: McpProxyInput): Promise { + const tool = createMcpProxyTool(manager); + const result = await tool.execute("call-id", params, undefined, undefined, {} as never); + const block = result.content[0]; + return block && block.type === "text" ? block.text : ""; +} + +/** A real in-memory MCP server exposing an `echo` tool, wired through the SDK client + adapter. */ +async function inMemoryEchoClient(): Promise { + const server = new McpServer({ name: "echo-server", version: "1.0.0" }); + server.registerTool( + "echo", + { description: "Echo the provided text back", inputSchema: { text: z.string() } }, + async ({ text }) => ({ content: [{ type: "text", text }] }), + ); + server.registerTool("boom", { description: "Always fails", inputSchema: {} }, async () => ({ + content: [{ type: "text", text: "tool blew up" }], + isError: true, + })); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + const client = new Client({ name: "test-client", version: "1.0.0" }); + await client.connect(clientTransport); + return adaptClient(client, "demo"); +} + +function managerWith(connector: McpConnector, idleTimeoutMs = 0): McpManager { + return new McpManager( + { mcpServers: { demo: { type: "stdio", command: "noop" } }, directTools: [], idleTimeoutMs }, + { connector }, + ); +} + +describe("prime-mcp config", () => { + let root: string; + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), "prime-mcp-")); + }); + + afterEach(async () => { + await rm(root, { recursive: true, force: true }); + }); + + test("parseToolRef splits server/tool and rejects malformed refs", () => { + expect(parseToolRef("server/tool")).toEqual({ server: "server", tool: "tool" }); + expect(parseToolRef("server/nested/tool")).toEqual({ server: "server", tool: "nested/tool" }); + expect(parseToolRef("notaref")).toBeUndefined(); + expect(parseToolRef("/leading")).toBeUndefined(); + expect(parseToolRef("trailing/")).toBeUndefined(); + }); + + test("candidate paths are project-first, then global", () => { + const paths = configCandidatePaths("/proj", "/home/user"); + expect(paths).toEqual([ + join("/proj", ".mcp.json"), + join("/proj", ".prime", "agent", "mcp.json"), + join("/home/user", ".prime", "agent", "mcp.json"), + ]); + }); + + test("merges global and project config with project overriding by name", async () => { + const home = join(root, "home"); + const cwd = join(root, "proj"); + await mkdir(join(home, ".prime", "agent"), { recursive: true }); + await mkdir(join(cwd, ".prime", "agent"), { recursive: true }); + + await writeFile( + join(home, ".prime", "agent", "mcp.json"), + JSON.stringify({ + mcpServers: { + globalOnly: { command: "global-cmd" }, + shared: { url: "https://global.example/mcp" }, + }, + directTools: ["globalOnly/a"], + idleTimeoutMs: 1000, + }), + ); + await writeFile( + join(cwd, ".prime", "agent", "mcp.json"), + JSON.stringify({ mcpServers: { projectPrime: { command: "prime-cmd" } } }), + ); + await writeFile( + join(cwd, ".mcp.json"), + JSON.stringify({ + mcpServers: { shared: { url: "https://project.example/mcp" } }, + directTools: ["shared/x"], + }), + ); + + const { config, sources } = await loadMcpConfig(cwd, home); + + expect(Object.keys(config.mcpServers).sort()).toEqual(["globalOnly", "projectPrime", "shared"]); + expect(config.mcpServers.shared).toEqual({ + type: "http", + url: "https://project.example/mcp", + headers: undefined, + }); + expect(config.mcpServers.globalOnly).toEqual({ + type: "stdio", + command: "global-cmd", + args: undefined, + env: undefined, + cwd: undefined, + }); + expect(config.directTools.sort()).toEqual(["globalOnly/a", "shared/x"]); + expect(config.idleTimeoutMs).toBe(1000); + // Highest precedence first. + expect(sources[0]).toBe(join(cwd, ".mcp.json")); + }); + + test("returns empty config when no files exist", async () => { + const { config, sources, warnings } = await loadMcpConfig(join(root, "nope"), join(root, "nohome")); + expect(config).toEqual({ mcpServers: {}, directTools: [] }); + expect(sources).toEqual([]); + expect(warnings).toEqual([]); + }); + + test("warns and skips a malformed file instead of failing the whole load", async () => { + const home = join(root, "home"); + await mkdir(join(home, ".prime", "agent"), { recursive: true }); + await writeFile( + join(home, ".prime", "agent", "mcp.json"), + JSON.stringify({ mcpServers: { good: { command: "ok" } } }), + ); + await writeFile(join(root, ".mcp.json"), "{ not json"); + + const { config, warnings } = await loadMcpConfig(root, home); + expect(Object.keys(config.mcpServers)).toEqual(["good"]); + expect(warnings.some((w) => /Invalid JSON/.test(w))).toBe(true); + }); + + test("warns when a server defines neither command nor url", async () => { + await writeFile(join(root, ".mcp.json"), JSON.stringify({ mcpServers: { bad: { foo: 1 } } })); + const { warnings } = await loadMcpConfig(root, join(root, "nohome")); + expect(warnings.some((w) => /either "command".*or "url"/.test(w))).toBe(true); + }); + + test("warns when a header value is not a string", async () => { + await writeFile( + join(root, ".mcp.json"), + JSON.stringify({ mcpServers: { remote: { url: "https://x/mcp", headers: { Authorization: 123 } } } }), + ); + const { warnings } = await loadMcpConfig(root, join(root, "nohome")); + expect(warnings.some((w) => /headers\.Authorization must be a string/.test(w))).toBe(true); + }); + + test("warns when both command and url are defined", async () => { + await writeFile( + join(root, ".mcp.json"), + JSON.stringify({ mcpServers: { mixed: { command: "x", url: "https://x/mcp" } } }), + ); + const { warnings } = await loadMcpConfig(root, join(root, "nohome")); + expect(warnings.some((w) => /defines both "command".*and "url"/.test(w))).toBe(true); + }); + + test("drops a global directTools entry when a project file redefines its server", async () => { + const home = join(root, "home"); + await mkdir(join(home, ".prime", "agent"), { recursive: true }); + await writeFile( + join(home, ".prime", "agent", "mcp.json"), + JSON.stringify({ mcpServers: { shared: { command: "trusted" } }, directTools: ["shared/echo"] }), + ); + await writeFile(join(root, ".mcp.json"), JSON.stringify({ mcpServers: { shared: { command: "attacker" } } })); + + const { config, warnings } = await loadMcpConfig(root, home); + expect(config.directTools).toEqual([]); + expect(warnings.some((w) => /Ignoring directTools entry "shared\/echo"/.test(w))).toBe(true); + }); +}); + +describe("prime-mcp content rendering", () => { + test("passes image blocks through as image content and keeps text", () => { + const rendered = renderMcpCall([ + { type: "text", text: "here is a chart" }, + { type: "image", data: "AAAA", mimeType: "image/png" }, + ]); + expect(rendered.content).toEqual([ + { type: "text", text: "here is a chart" }, + { type: "image", data: "AAAA", mimeType: "image/png" }, + ]); + }); + + test("renders resource_link blocks with their uri instead of a placeholder", () => { + const rendered = renderMcpCall([{ type: "resource_link", name: "report", uri: "file:///report.md" }]); + expect(rendered.text).toContain("file:///report.md"); + expect(rendered.text).toContain("report"); + }); + + test("falls back to structuredContent when there is no content", () => { + const rendered = renderMcpCall([], { answer: 42 }); + expect(rendered.text).toContain("answer"); + expect(rendered.text).toContain("42"); + }); + + test("ignores nullish content blocks instead of failing the whole render", () => { + const rendered = renderMcpCall([null, undefined, { type: "text", text: "ok" }]); + expect(rendered.content).toEqual([{ type: "text", text: "ok" }]); + expect(rendered.text).toBe("ok"); + }); + + test("bounds the error summary text so a huge payload can't flood the transcript", () => { + const rendered = renderMcpCall([{ type: "text", text: "x".repeat(100_000) }]); + expect(rendered.text.length).toBeLessThan(30_000); + expect(rendered.text).toContain("[Output truncated"); + }); +}); + +describe("prime-mcp direct tool naming", () => { + test("keeps short names verbatim", () => { + expect(directToolName("demo", "echo")).toBe("mcp__demo__echo"); + }); + + test("caps names that exceed the provider limit while staying unique", () => { + const long = directToolName("server", "t".repeat(80)); + expect(long.length).toBeLessThanOrEqual(64); + // Distinct long refs must not collapse to the same capped name. + expect(directToolName("server", `${"t".repeat(80)}-other`)).not.toBe(long); + }); +}); + +describe("prime-mcp proxy tool", () => { + test("lists servers, lists tools, describes and calls through the proxy", async () => { + const manager = managerWith(async () => inMemoryEchoClient()); + + const servers = await callProxy(manager, { action: "list_servers" }); + expect(servers).toContain("demo"); + + const tools = await callProxy(manager, { action: "list_tools", server: "demo" }); + expect(tools).toContain("echo"); + + const described = await callProxy(manager, { action: "describe", server: "demo", tool: "echo" }); + expect(described).toContain("echo"); + expect(described).toContain("text"); + + const called = await callProxy(manager, { + action: "call", + server: "demo", + tool: "echo", + arguments: { text: "hello mcp" }, + }); + expect(called).toBe("hello mcp"); + + await manager.disconnectAll(); + }); + + test("throws when an MCP tool returns isError", async () => { + const manager = managerWith(async () => inMemoryEchoClient()); + await expect(callProxy(manager, { action: "call", server: "demo", tool: "boom", arguments: {} })).rejects.toThrow( + /tool blew up/, + ); + await manager.disconnectAll(); + }); + + test("renders structuredContent when a call returns no text content", async () => { + const connector: McpConnector = async () => ({ + listTools: async () => [{ name: "data", inputSchema: { type: "object" } }], + callTool: async () => ({ content: [], isError: false, structuredContent: { answer: 42 } }), + close: async () => {}, + }); + const manager = managerWith(connector); + const out = await callProxy(manager, { action: "call", server: "demo", tool: "data", arguments: {} }); + expect(out).toContain("answer"); + expect(out).toContain("42"); + await manager.disconnectAll(); + }); + + test("reports when no servers are configured", async () => { + const manager = new McpManager( + { mcpServers: {}, directTools: [] }, + { connector: async () => inMemoryEchoClient() }, + ); + const out = await callProxy(manager, { action: "list_servers" }); + expect(out).toContain("No MCP servers are configured"); + }); +}); + +describe("prime-mcp manager lifecycle", () => { + test("reconnects once and retries when listing tools fails on a dead transport", async () => { + let connectCount = 0; + let failNextList = true; + const connector: McpConnector = async () => { + connectCount++; + return { + listTools: async () => { + if (failNextList) { + failNextList = false; + throw new Error("transport closed"); + } + return [{ name: "echo", inputSchema: { type: "object" } }]; + }, + callTool: async () => { + return { content: [{ type: "text", text: "ok" }], isError: false }; + }, + close: async () => {}, + }; + }; + + const manager = managerWith(connector); + const result = await manager.listTools("demo"); + + expect(result.map((tool) => tool.name)).toEqual(["echo"]); + expect(connectCount).toBe(2); + }); + + test("does not retry tool calls after transport errors to avoid duplicate side effects", async () => { + let connectCount = 0; + let callCount = 0; + const connector: McpConnector = async () => { + connectCount++; + return { + listTools: async () => [{ name: "mutate", inputSchema: { type: "object" } }], + callTool: async () => { + callCount++; + throw new Error("socket hang up"); + }, + close: async () => {}, + }; + }; + + const manager = managerWith(connector); + await expect(manager.callTool("demo", "mutate", {})).rejects.toThrow(/socket hang up/); + expect(callCount).toBe(1); + expect(connectCount).toBe(1); + }); + + test("does not retry when a call fails with a non-transport error", async () => { + let connectCount = 0; + const connector: McpConnector = async () => { + connectCount++; + return { + listTools: async () => [], + callTool: async () => { + throw new Error("invalid arguments"); + }, + close: async () => {}, + }; + }; + + const manager = managerWith(connector); + await expect(manager.callTool("demo", "echo", {})).rejects.toThrow(/invalid arguments/); + expect(connectCount).toBe(1); + }); + + test("closes a connection that resolves after disconnect was requested", async () => { + let closeCount = 0; + let resolveConnect: ((client: McpClientLike) => void) | undefined; + const pending = new Promise((resolve) => { + resolveConnect = resolve; + }); + const connector: McpConnector = async () => pending; + + const manager = managerWith(connector); + const op = manager.listTools("demo").catch(() => undefined); + const dis = manager.disconnectAll(); + resolveConnect?.({ + listTools: async () => [], + callTool: async () => ({ content: [], isError: false }), + close: async () => { + closeCount++; + }, + }); + await op; + await dis; + + expect(closeCount).toBe(1); + expect(manager.getStatus("demo")?.state).toBe("disconnected"); + }); + + test("aborts an in-flight connect when disconnecting instead of waiting it out", async () => { + let aborted = false; + const connector: McpConnector = (_name, _config, signal) => + new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => { + aborted = true; + reject(new Error("aborted")); + }); + }); + + const manager = managerWith(connector); + const op = manager.listTools("demo").catch(() => undefined); + await manager.disconnect("demo"); + await op; + + expect(aborted).toBe(true); + }); + + test("a cancelled call stops waiting on a connect without aborting it for others", async () => { + let connectAborted = false; + let resolveConnect: ((client: McpClientLike) => void) | undefined; + const pending = new Promise((resolve) => { + resolveConnect = resolve; + }); + const connector: McpConnector = (_name, _config, signal) => { + signal?.addEventListener("abort", () => { + connectAborted = true; + }); + return pending; + }; + + const manager = managerWith(connector); + const controller = new AbortController(); + const cancelled = manager.listTools("demo", controller.signal); + controller.abort(); + await expect(cancelled).rejects.toThrow(/abort/i); + // The shared connect must still be live for other callers. + expect(connectAborted).toBe(false); + + resolveConnect?.({ + listTools: async () => [{ name: "echo", inputSchema: { type: "object" } }], + callTool: async () => ({ content: [], isError: false }), + close: async () => {}, + }); + const tools = await manager.listTools("demo"); + expect(tools.map((t) => t.name)).toEqual(["echo"]); + await manager.disconnectAll(); + }); + + test("treats inherited Object keys like toString as unknown servers", () => { + const manager = managerWith(async () => inMemoryEchoClient()); + expect(manager.hasServer("toString")).toBe(false); + expect(manager.hasServer("constructor")).toBe(false); + expect(manager.hasServer("demo")).toBe(true); + }); + + test("does not double-end the old connection when reconnecting after a list failure cannot reconnect", async () => { + let connectCount = 0; + const closed: number[] = []; + let releaseSlow!: () => void; + let slowStarted!: () => void; + const slowGate = new Promise((resolve) => { + releaseSlow = resolve; + }); + const started = new Promise((resolve) => { + slowStarted = resolve; + }); + const connector: McpConnector = async () => { + connectCount++; + const id = connectCount; + if (id === 2) throw new Error("connection refused"); + return { + listTools: async () => { + throw new Error("transport closed"); + }, + callTool: async () => { + slowStarted(); + await slowGate; + return { content: [{ type: "text", text: `slow-${id}` }], isError: false }; + }, + close: async () => { + closed.push(id); + }, + }; + }; + + const manager = managerWith(connector); + const slow = manager.callTool("demo", "slow", {}); + await started; + + await expect(manager.listTools("demo")).rejects.toThrow(/connection refused/); + expect(closed).not.toContain(1); + + releaseSlow(); + await expect(slow).resolves.toMatchObject({ isError: false }); + expect(closed.filter((id) => id === 1)).toEqual([1]); + }); + + test("passes the caller signal through reconnect waits", async () => { + const connector: McpConnector = (_name, _config, signal) => + new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => reject(new Error("aborted"))); + }); + const manager = managerWith(connector); + const controller = new AbortController(); + controller.abort(); + + const reconnect = manager.reconnect("demo", controller.signal); + try { + const outcome = await Promise.race([ + reconnect.then( + () => "resolved", + (error: unknown) => error, + ), + new Promise<"pending">((resolve) => { + setTimeout(() => resolve("pending"), 0); + }), + ]); + + expect(outcome).toBeInstanceOf(Error); + expect(String((outcome as Error).message)).toMatch(/abort/i); + } finally { + await manager.disconnectAll(); + } + }); + + test("disconnect waits for in-flight operations before closing the client", async () => { + let closeCount = 0; + let releaseSlow!: () => void; + let slowStarted!: () => void; + const slowGate = new Promise((resolve) => { + releaseSlow = resolve; + }); + const started = new Promise((resolve) => { + slowStarted = resolve; + }); + const connector: McpConnector = async () => ({ + listTools: async () => [], + callTool: async () => { + slowStarted(); + await slowGate; + return { content: [{ type: "text", text: "done" }], isError: false }; + }, + close: async () => { + closeCount++; + }, + }); + const manager = managerWith(connector); + const slow = manager.callTool("demo", "slow", {}); + await started; + + await manager.disconnect("demo"); + expect(closeCount).toBe(0); + + releaseSlow(); + await expect(slow).resolves.toMatchObject({ isError: false }); + expect(closeCount).toBe(1); + }); + + test("a parallel call keeps its connection alive while a sibling list reconnects", async () => { + let connectCount = 0; + const closed: number[] = []; + let releaseSlow!: () => void; + const slowGate = new Promise((resolve) => { + releaseSlow = resolve; + }); + const connector: McpConnector = async () => { + connectCount++; + const id = connectCount; + return { + listTools: async () => { + if (id === 1) throw new Error("transport closed"); + return [{ name: "ok", inputSchema: { type: "object" } }]; + }, + callTool: async (tool) => { + if (tool === "slow") { + await slowGate; + return { content: [{ type: "text", text: `slow-${id}` }], isError: false }; + } + return { content: [{ type: "text", text: `ok-${id}` }], isError: false }; + }, + close: async () => { + closed.push(id); + }, + }; + }; + + const manager = managerWith(connector); + // "slow" parks in-flight on connection 1; listTools forces a reconnect. + const slow = manager.callTool("demo", "slow", {}); + const a = await manager.listTools("demo"); + + expect(a.map((tool) => tool.name)).toEqual(["ok"]); + // The slow sibling still holds connection 1, so it must not be closed yet. + expect(closed).not.toContain(1); + + releaseSlow(); + const b = await slow; + expect(b.isError).toBe(false); + // Once the sibling drains, connection 1 is closed exactly once. + expect(closed.filter((id) => id === 1)).toEqual([1]); + }); + + test("warns and skips when two directTools refs collide on a sanitized name", async () => { + const connector: McpConnector = async () => ({ + listTools: async () => [ + { name: "foo-bar", inputSchema: { type: "object" } }, + { name: "foo_bar", inputSchema: { type: "object" } }, + ], + callTool: async () => ({ content: [], isError: false }), + close: async () => {}, + }); + const manager = managerWith(connector); + + const registeredNames: string[] = []; + const warnings: string[] = []; + const pi = { registerTool: (tool: ToolDefinition) => registeredNames.push(tool.name) } as unknown as ExtensionAPI; + + await registerDirectTools(pi, manager, ["demo/foo-bar", "demo/foo_bar"], (m) => warnings.push(m)); + + expect(registeredNames).toEqual(["mcp__demo__foo_bar"]); + expect(warnings.some((w) => w.includes("collides"))).toBe(true); + await manager.disconnectAll(); + }); + + test("registers a deferred direct tool on connection errors and upgrades it on retry", async () => { + let listToolsAvailable = false; + const connector: McpConnector = async () => ({ + listTools: async () => { + if (!listToolsAvailable) throw new Error("connection refused"); + return [ + { + name: "echo", + description: "Echo text", + inputSchema: { type: "object", properties: { text: { type: "string" } } }, + }, + ]; + }, + callTool: async () => ({ content: [{ type: "text", text: "called" }], isError: false }), + close: async () => {}, + }); + const manager = managerWith(connector); + + const registeredTools: ToolDefinition[] = []; + const warnings: string[] = []; + const pi = { registerTool: (tool: ToolDefinition) => registeredTools.push(tool) } as unknown as ExtensionAPI; + + await registerDirectTools(pi, manager, ["demo/echo"], (m) => warnings.push(m)); + expect(registeredTools.map((tool) => tool.name)).toEqual(["mcp__demo__echo"]); + expect(warnings.some((w) => w.includes("deferred schema"))).toBe(true); + + listToolsAvailable = true; + await manager.reconnect("demo"); + await registerDirectTools(pi, manager, ["demo/echo"], (m) => warnings.push(m)); + + expect(registeredTools.map((tool) => tool.name)).toEqual(["mcp__demo__echo", "mcp__demo__echo"]); + expect(registeredTools[1]?.parameters).toEqual({ + type: "object", + properties: { text: { type: "string" } }, + }); + await manager.disconnectAll(); + }); + + test("disconnects an idle server after the idle timeout", async () => { + vi.useFakeTimers(); + try { + let closeCount = 0; + const connector: McpConnector = async () => ({ + listTools: async () => [], + callTool: async () => ({ content: [], isError: false }), + close: async () => { + closeCount++; + }, + }); + + const manager = managerWith(connector, 1000); + await manager.listTools("demo"); + expect(manager.getStatus("demo")?.state).toBe("connected"); + + await vi.advanceTimersByTimeAsync(1000); + + expect(closeCount).toBe(1); + expect(manager.getStatus("demo")?.state).toBe("disconnected"); + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 4dfbf3d254..c9015ecc25 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -20,6 +20,11 @@ "@earendil-works/pi-agent-old/*": ["./packages/agent-old/src/*"] } }, - "include": ["packages/*/src/**/*", "packages/*/test/**/*", "packages/coding-agent/examples/**/*"], + "include": [ + "packages/*/src/**/*", + "packages/*/test/**/*", + "packages/coding-agent/examples/**/*", + "packages/coding-agent/extensions/**/*" + ], "exclude": ["**/dist/**"] }