From 31536400e462a2aa2d4e700183ad2d96151ec2ed Mon Sep 17 00:00:00 2001 From: Abhyudaya Baiju Tharakan Date: Fri, 9 Oct 2026 03:36:57 +0530 Subject: [PATCH] feat(mcp): add opt-in tool contract digests and pin checks Add schema digests to /mcp tools/list on Flask and the edge Worker and reject a mismatched X-MultiLLM-MCP-Contract pin with 409 before dispatch, behind MCP_CONTRACT_DIGESTS_ENABLED, default off. The catalogue script gains --baseline and --diff. --- docs/mcp-contract-baseline.json | 2699 ++++++++++++++++++ docs/mcp-contract-drift.md | 106 + package.json | 2 +- routes/knowledge.py | 9 +- routes/knowledge_mcp.py | 25 + scripts/build_knowledge_mcp_catalogue.py | 29 +- services/mcp_contract_drift.py | 213 ++ tests/fixtures/secret_firewall_coverage.json | 1 + tests/test_mcp_contract_drift.py | 282 ++ tests/test_mcp_contract_drift_worker.mjs | 179 ++ worker/container-env.mjs | 1 + worker/knowledge-edge.mjs | 8 +- worker/knowledge/contract-drift.mjs | 99 + worker/knowledge/native.mjs | 3 + 14 files changed, 3648 insertions(+), 8 deletions(-) create mode 100644 docs/mcp-contract-baseline.json create mode 100644 docs/mcp-contract-drift.md create mode 100644 services/mcp_contract_drift.py create mode 100644 tests/test_mcp_contract_drift.py create mode 100644 tests/test_mcp_contract_drift_worker.mjs create mode 100644 worker/knowledge/contract-drift.mjs diff --git a/docs/mcp-contract-baseline.json b/docs/mcp-contract-baseline.json new file mode 100644 index 00000000..90ed584e --- /dev/null +++ b/docs/mcp-contract-baseline.json @@ -0,0 +1,2699 @@ +{ + "format": "multillm-mcp-contract-v1", + "contract_version": "1.0.0", + "vectors": [ + { + "definition": { + "name": "knowledge_test", + "inputSchema": { + "type": "object", + "properties": { + "b": { + "type": [ + "string", + "null" + ] + }, + "a": { + "minimum": 1.0, + "x-vendor": { + "東京": "café", + "values": [ + true, + null, + -0.0, + 1e-07 + ] + } + } + }, + "required": [ + "b", + "a" + ] + }, + "outputSchema": { + "type": "string" + } + }, + "contract_version": "1.0.0", + "canonical": "[\"object\",[[\"contractVersion\",[\"string\",\"1.0.0\"]],[\"inputSchema\",[\"object\",[[\"properties\",[\"object\",[[\"a\",[\"object\",[[\"minimum\",[\"number\",\"3ff0000000000000\"]],[\"x-vendor\",[\"object\",[[\"values\",[\"array\",[[\"boolean\",true],[\"null\"],[\"number\",\"0000000000000000\"],[\"number\",\"3e7ad7f29abcaf48\"]]]],[\"東京\",[\"string\",\"café\"]]]]]]]],[\"b\",[\"object\",[[\"type\",[\"array\",[[\"string\",\"string\"],[\"string\",\"null\"]]]]]]]]]],[\"required\",[\"array\",[[\"string\",\"b\"],[\"string\",\"a\"]]]],[\"type\",[\"string\",\"object\"]]]]],[\"name\",[\"string\",\"knowledge_test\"]],[\"outputSchema\",[\"object\",[[\"type\",[\"string\",\"string\"]]]]]]]", + "digest": "86ca5e6572acf7096006d501b4eaebb0a8c5344672ff34025f553fa90e0554ae" + }, + { + "definition": { + "name": "knowledge_😀", + "inputSchema": { + "": 1, + "😀": 2, + "type": "object", + "anyOf": [ + { + "type": "string" + }, + { + "type": "number" + } + ] + } + }, + "contract_version": "1.0.0", + "canonical": "[\"object\",[[\"contractVersion\",[\"string\",\"1.0.0\"]],[\"inputSchema\",[\"object\",[[\"anyOf\",[\"array\",[[\"object\",[[\"type\",[\"string\",\"string\"]]]],[\"object\",[[\"type\",[\"string\",\"number\"]]]]]]],[\"type\",[\"string\",\"object\"]],[\"\",[\"number\",\"3ff0000000000000\"]],[\"😀\",[\"number\",\"4000000000000000\"]]]]],[\"name\",[\"string\",\"knowledge_😀\"]],[\"outputSchema\",[\"null\"]]]]", + "digest": "b581ac9b31927692d5fb4bb84ad51081c9e0235a17513ccdec91dc1b482f231f" + }, + { + "definition": { + "name": "knowledge_test", + "inputSchema": true + }, + "contract_version": "1.0.0", + "canonical": "[\"object\",[[\"contractVersion\",[\"string\",\"1.0.0\"]],[\"inputSchema\",[\"boolean\",true]],[\"name\",[\"string\",\"knowledge_test\"]],[\"outputSchema\",[\"null\"]]]]", + "digest": "bed47def1f7c19e8d07d34874b2d486f799d4a25349711cda9102a208f52c0d3" + } + ], + "tools": [ + { + "definition": { + "name": "knowledge_context", + "description": "Retrieve cited technical excerpts with explicit version evidence and gaps.", + "inputSchema": { + "type": "object", + "required": [ + "query" + ], + "additionalProperties": false, + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "product": { + "type": "string", + "maxLength": 100 + }, + "version": { + "type": "string", + "maxLength": 80 + }, + "repository": { + "type": "string", + "maxLength": 200, + "pattern": "^[\\w.-]+/[\\w.-]+$" + }, + "mode": { + "type": "string", + "enum": [ + "economy", + "smart", + "deep" + ], + "default": "smart" + }, + "token_budget": { + "type": "integer", + "minimum": 256, + "maximum": 16000, + "default": 6000 + }, + "freshness": { + "type": "string", + "enum": [ + "normal", + "fresh" + ], + "default": "normal" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "b1e612922e794405c5da6639992111a9c60ab0a0e93665d03a533fd826c4b666" + }, + { + "definition": { + "name": "knowledge_search", + "description": "Search technical sources and inspect normalized retrieval diagnostics.", + "inputSchema": { + "type": "object", + "required": [ + "query" + ], + "additionalProperties": false, + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "product": { + "type": "string", + "maxLength": 100 + }, + "version": { + "type": "string", + "maxLength": 80 + }, + "repository": { + "type": "string", + "maxLength": 200, + "pattern": "^[\\w.-]+/[\\w.-]+$" + }, + "mode": { + "type": "string", + "enum": [ + "economy", + "smart", + "deep" + ], + "default": "smart" + }, + "token_budget": { + "type": "integer", + "minimum": 256, + "maximum": 16000, + "default": 6000 + }, + "freshness": { + "type": "string", + "enum": [ + "normal", + "fresh" + ], + "default": "normal" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "0b3d1e62a1c5aba33599c48e7e084a8fad9ee6e16111e30cefeb15242260921e" + }, + { + "definition": { + "name": "knowledge_alexandria_search", + "description": "Discover Alexandria capabilities for free. Only returned quote ids can be inspected or executed.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 10, + "default": 5 + } + }, + "required": [ + "query" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "cafc8da9f81dfc89fab02c5132223069d65089cd959d071e7538234ed7d49810" + }, + { + "definition": { + "name": "knowledge_alexandria_inspect", + "description": "Inspect a discovered capability's inputs and response contract for free.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "quote_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + } + }, + "required": [ + "quote_id" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "7a54ca8b0bada37be5dc11f905989e005c43d525d78a7a8f753ffebc1778d259" + }, + { + "definition": { + "name": "knowledge_alexandria_execute", + "description": "Spend Firecrawl credits to execute a recently discovered quote. Choose options from its contract; reserve_credits counts against the allowance but is not an upstream price cap. Per-record pricing requires accept_variable_cost=true. Reuse request_id for the same request; never retry with a new id after an unknown outcome. Report the returned cost to the user.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "quote_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + }, + "request_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + }, + "options": { + "type": "object" + }, + "reserve_credits": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "accept_variable_cost": { + "type": "boolean", + "default": false + } + }, + "required": [ + "quote_id", + "request_id", + "options", + "reserve_credits" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "5a463eb856ce9a6fefd19a31a77a7028857baad608fbc4842bb45674fcc8027f" + }, + { + "definition": { + "name": "knowledge_alexandria_receipt", + "description": "Read a previous request's credit receipt without executing the provider again. No charge.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "request_id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + } + }, + "required": [ + "request_id" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + } + }, + "digest": "3b76a3b68d7306dbc4d528f999cef41cecf87ad931342f2a18e5273b5e1eec7e" + }, + { + "definition": { + "name": "knowledge_context7_resolve_library", + "description": "Context7: find libraries by name and return their Context7 IDs, versions, snippet counts and trust scores. Use the returned id with knowledge_context7_docs.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "libraryName", + "query" + ], + "properties": { + "libraryName": { + "type": "string", + "minLength": 1, + "maxLength": 200, + "description": "Library or product name, for example react, next.js or express." + }, + "query": { + "type": "string", + "minLength": 1, + "maxLength": 1000, + "description": "The task or question, used to rank matching libraries." + }, + "fast": { + "type": "boolean", + "description": "Skip Context7's reranking for lower latency." + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "e6e2c1cbdce24860e06bd7589854568d9e52d40ecd03aaafbba816c389491e64" + }, + { + "definition": { + "name": "knowledge_context7_docs", + "description": "Context7: up-to-date documentation and code examples for one library, ranked for a question. Accepts /owner/repo or /owner/repo/version IDs from knowledge_context7_resolve_library.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "libraryId", + "query" + ], + "properties": { + "libraryId": { + "type": "string", + "pattern": "^/[^\\s?#]{1,300}$", + "description": "Context7 library ID such as /vercel/next.js or /vercel/next.js/v15.1.8." + }, + "query": { + "type": "string", + "minLength": 1, + "maxLength": 1000, + "description": "What you need from the documentation." + }, + "type": { + "type": "string", + "enum": [ + "json", + "txt" + ], + "default": "json", + "description": "json returns structured snippets; txt returns LLM-ready text." + }, + "fast": { + "type": "boolean", + "description": "Skip Context7's reranking for lower latency." + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "be8bc7b689eec0fdfc62200b863de277ae4b196b3dd1df3e0e00fe11657998ba" + }, + { + "definition": { + "name": "knowledge_exa_search", + "description": "Exa: web search with full Exa options (search type, result count, categories, domain and date filters, and page text, highlights or summaries under contents). Units grow with deep search types, results above 10 and content pages; keys without knowledge:manage may request at most 25 results and 5 subpages.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + }, + "type": { + "type": "string", + "enum": [ + "auto", + "fast", + "instant", + "deep-lite", + "deep", + "deep-reasoning" + ], + "default": "auto" + }, + "numResults": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 10, + "description": "Results to return. Above 25 requires knowledge:manage." + }, + "category": { + "type": "string", + "enum": [ + "company", + "research paper", + "news", + "pdf", + "github", + "personal site", + "people", + "financial report" + ] + }, + "includeDomains": { + "type": "array", + "maxItems": 1200, + "items": { + "type": "string", + "maxLength": 300 + } + }, + "excludeDomains": { + "type": "array", + "maxItems": 1200, + "items": { + "type": "string", + "maxLength": 300 + } + }, + "startPublishedDate": { + "type": "string", + "maxLength": 40 + }, + "endPublishedDate": { + "type": "string", + "maxLength": 40 + }, + "startCrawlDate": { + "type": "string", + "maxLength": 40 + }, + "endCrawlDate": { + "type": "string", + "maxLength": 40 + }, + "includeText": { + "type": "array", + "maxItems": 5, + "items": { + "type": "string", + "maxLength": 200 + } + }, + "excludeText": { + "type": "array", + "maxItems": 5, + "items": { + "type": "string", + "maxLength": 200 + } + }, + "userLocation": { + "type": "string", + "maxLength": 8 + }, + "moderation": { + "type": "boolean" + }, + "additionalQueries": { + "type": "array", + "maxItems": 10, + "items": { + "type": "string", + "maxLength": 2000 + } + }, + "outputSchema": { + "type": "object" + }, + "contents": { + "type": "object", + "description": "Exa contents options, for example {\"highlights\": true} or {\"text\": {\"maxCharacters\": 10000}, \"summary\": true, \"maxAgeHours\": 0}." + } + } + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "77bd6e5fb82f502ecc4fa654532228b3ff623ac1f6c74a5cb9db53e853700ad1" + }, + { + "definition": { + "name": "knowledge_exa_contents", + "description": "Exa: fetch clean page text, highlights or summaries for known URLs (crawl), optionally forcing a fresh crawl with maxAgeHours 0. Units are charged per 10 pages per content type; keys without knowledge:manage may fetch at most 25 URLs with 5 subpages each.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "urls" + ], + "properties": { + "urls": { + "type": "array", + "minItems": 1, + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 2048 + } + }, + "text": { + "type": [ + "boolean", + "object" + ] + }, + "highlights": { + "type": [ + "boolean", + "object" + ] + }, + "summary": { + "type": [ + "boolean", + "object" + ] + }, + "maxAgeHours": { + "type": "integer", + "minimum": -1, + "maximum": 100000 + }, + "livecrawlTimeout": { + "type": "integer", + "minimum": 1000, + "maximum": 90000 + }, + "subpages": { + "type": "integer", + "minimum": 0, + "maximum": 100 + }, + "subpageTarget": { + "type": [ + "string", + "array" + ] + }, + "extras": { + "type": "object" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "2ea7ab1fd00e8534c414da2452b15bcc1e11a03355dfd171ac1959bff7722e2a" + }, + { + "definition": { + "name": "knowledge_exa_code_context", + "description": "Exa Code: code examples and API usage context for libraries, SDKs and frameworks, gathered from GitHub, docs and Q&A.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + }, + "tokensNum": { + "anyOf": [ + { + "type": "integer", + "minimum": 50, + "maximum": 100000 + }, + { + "type": "string", + "enum": [ + "dynamic" + ] + } + ], + "default": "dynamic" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "b5a10f4339fdf177938fe651da268122d55e34b0f48578025d771e27b314eef7" + }, + { + "definition": { + "name": "knowledge_exa_answer", + "description": "Exa: a generated answer to a question with the web sources it cites; optionally structured by outputSchema. Including source text costs an extra unit.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + }, + "text": { + "type": "boolean", + "description": "Include full text of the cited sources." + }, + "systemPrompt": { + "type": "string", + "maxLength": 10000 + }, + "outputSchema": { + "type": "object" + }, + "userLocation": { + "type": "string", + "maxLength": 8 + } + } + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "4079b6755a8b00df98ac19763170dd600fa7f1b015c30deef205720020a3898b" + }, + { + "definition": { + "name": "knowledge_firecrawl_scrape", + "description": "Firecrawl: scrape one page into markdown, HTML, links, screenshots, summaries or JSON, with waits, location and proxy options. LLM formats (json, summary, changeTracking) and enhanced proxies cost more units. Custom headers, browser actions, skipped TLS checks and enhanced or stealth proxies require knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string", + "maxLength": 2048 + }, + "formats": { + "type": "array", + "maxItems": 10, + "items": { + "type": [ + "string", + "object" + ] + } + }, + "onlyMainContent": { + "type": "boolean" + }, + "includeTags": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 200 + } + }, + "excludeTags": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 200 + } + }, + "maxAge": { + "type": "integer", + "minimum": 0 + }, + "headers": { + "type": "object", + "description": "Requires knowledge:manage." + }, + "waitFor": { + "type": "integer", + "minimum": 0, + "maximum": 60000 + }, + "mobile": { + "type": "boolean" + }, + "skipTlsVerification": { + "type": "boolean", + "description": "Requires knowledge:manage." + }, + "timeout": { + "type": "integer", + "minimum": 1000, + "maximum": 120000 + }, + "parsers": { + "type": "array", + "maxItems": 10 + }, + "actions": { + "type": "array", + "maxItems": 50, + "items": { + "type": "object" + }, + "description": "Requires knowledge:manage." + }, + "location": { + "type": "object" + }, + "removeBase64Images": { + "type": "boolean" + }, + "blockAds": { + "type": "boolean" + }, + "proxy": { + "type": "string", + "enum": [ + "basic", + "stealth", + "enhanced", + "auto" + ], + "description": "enhanced and stealth require knowledge:manage and cost up to 5 units per page." + }, + "storeInCache": { + "type": "boolean" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "fefc031664b32966bfef7f56c1e9730888870eebcc234a5085a9886650b10d4f" + }, + { + "definition": { + "name": "knowledge_firecrawl_search", + "description": "Firecrawl: search the web, news, images or GitHub/research categories and optionally scrape each result with scrapeOptions. Units: 2 per 10 results plus each scraped page; keys without knowledge:manage may request at most 25 results.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 1000 + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 5, + "description": "Results to return. Above 25 requires knowledge:manage." + }, + "sources": { + "type": "array", + "maxItems": 3, + "items": { + "type": [ + "string", + "object" + ] + } + }, + "categories": { + "type": "array", + "maxItems": 5, + "items": { + "type": [ + "string", + "object" + ] + } + }, + "tbs": { + "type": "string", + "maxLength": 100 + }, + "location": { + "type": "string", + "maxLength": 200 + }, + "country": { + "type": "string", + "maxLength": 8 + }, + "includeDomains": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 300 + } + }, + "excludeDomains": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 300 + } + }, + "timeout": { + "type": "integer", + "minimum": 1000, + "maximum": 120000 + }, + "ignoreInvalidURLs": { + "type": "boolean" + }, + "scrapeOptions": { + "type": "object" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "40a537895075604146169d292d1010c946f46b952e10288cb75570c5cfacfe75" + }, + { + "definition": { + "name": "knowledge_firecrawl_map", + "description": "Firecrawl: list the URLs of a website from its sitemap, search results and links, optionally ranked by a search term.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string", + "maxLength": 2048 + }, + "search": { + "type": "string", + "maxLength": 1000 + }, + "sitemap": { + "type": "string", + "enum": [ + "skip", + "include", + "only" + ] + }, + "includeSubdomains": { + "type": "boolean" + }, + "ignoreQueryParameters": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + }, + "timeout": { + "type": "integer", + "minimum": 1000, + "maximum": 120000 + }, + "location": { + "type": "object" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "98e5b9d51316ff0dd8ac9a2be6f491e7802fd497089c8075338cd7b426c958be" + }, + { + "definition": { + "name": "knowledge_firecrawl_crawl", + "description": "Firecrawl: start an asynchronous crawl of a website and return its job id; read pages with knowledge_firecrawl_crawl_status. Units are charged per page limit and page cost; keys without knowledge:manage may crawl at most 100 pages and cannot follow external links.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "url" + ], + "properties": { + "url": { + "type": "string", + "maxLength": 2048 + }, + "prompt": { + "type": "string", + "maxLength": 10000 + }, + "includePaths": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 500 + } + }, + "excludePaths": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 500 + } + }, + "maxDiscoveryDepth": { + "type": "integer", + "minimum": 0, + "maximum": 100 + }, + "sitemap": { + "type": "string", + "enum": [ + "skip", + "include", + "only" + ] + }, + "ignoreQueryParameters": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 10000, + "default": 10, + "description": "Maximum pages. Above 100 requires knowledge:manage." + }, + "crawlEntireDomain": { + "type": "boolean" + }, + "allowExternalLinks": { + "type": "boolean", + "description": "Requires knowledge:manage." + }, + "allowSubdomains": { + "type": "boolean" + }, + "delay": { + "type": "number", + "minimum": 0, + "maximum": 60 + }, + "maxConcurrency": { + "type": "integer", + "minimum": 1, + "maximum": 100 + }, + "scrapeOptions": { + "type": "object" + } + } + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "4a825599d601b705a60f080d237268e7566258f0619f805dcb34700f2d8e3d52" + }, + { + "definition": { + "name": "knowledge_firecrawl_crawl_status", + "description": "Firecrawl: status and scraped pages of a crawl started with knowledge_firecrawl_crawl. No allowance units.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9-]{1,80}$" + }, + "skip": { + "type": "integer", + "minimum": 0, + "maximum": 1000000, + "description": "Pages to skip, from the previous response's next link." + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "58f771fa0a5b74776356422d566140f857521db9b458d4b9c65cd6287d74f19f" + }, + { + "definition": { + "name": "knowledge_firecrawl_extract", + "description": "Firecrawl: start an asynchronous LLM extraction of structured data from up to 10 URLs with a prompt or JSON schema; read it with knowledge_firecrawl_extract_status. Units are charged per URL, and a glob reserves 25 pages. Globs, web search and external links require knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "urls" + ], + "properties": { + "urls": { + "type": "array", + "minItems": 1, + "maxItems": 10, + "items": { + "type": "string", + "maxLength": 2048 + }, + "description": "Page URLs. A URL ending in /* (a glob) requires knowledge:manage." + }, + "prompt": { + "type": "string", + "maxLength": 10000 + }, + "systemPrompt": { + "type": "string", + "maxLength": 10000 + }, + "schema": { + "type": "object" + }, + "enableWebSearch": { + "type": "boolean", + "description": "Requires knowledge:manage." + }, + "ignoreSitemap": { + "type": "boolean" + }, + "includeSubdomains": { + "type": "boolean" + }, + "allowExternalLinks": { + "type": "boolean", + "description": "Requires knowledge:manage." + }, + "showSources": { + "type": "boolean" + }, + "ignoreInvalidURLs": { + "type": "boolean" + }, + "scrapeOptions": { + "type": "object" + } + } + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "9fab350cad37d179725884e20704fdb0a974ed669b0ed4c394aea08418e22fa6" + }, + { + "definition": { + "name": "knowledge_firecrawl_extract_status", + "description": "Firecrawl: status and data of an extraction started with knowledge_firecrawl_extract. No allowance units.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "id" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9-]{1,80}$" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "8851ff09fb3fbe6cec37ea9d254712398575fda1ced997bf5434375871e2394e" + }, + { + "definition": { + "name": "knowledge_deepwiki_structure", + "description": "DeepWiki: the documentation topics DeepWiki has generated for a public GitHub repository.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "repoName" + ], + "properties": { + "repoName": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "efa01f496c5274561f24fbdfc6c6ec3a443cb1a3a604cb701739f98ea55a4ad3" + }, + { + "definition": { + "name": "knowledge_deepwiki_contents", + "description": "DeepWiki: the full generated documentation of a public GitHub repository.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "repoName" + ], + "properties": { + "repoName": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$" + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "e7a6aea36095a707a1551348011132572fb5904aa2cb653105917cb0928d43ff" + }, + { + "definition": { + "name": "knowledge_deepwiki_ask", + "description": "DeepWiki: an AI answer grounded in the DeepWiki of one or up to 10 public GitHub repositories.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "repoName", + "question" + ], + "properties": { + "repoName": { + "anyOf": [ + { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$" + }, + { + "type": "array", + "minItems": 1, + "maxItems": 10, + "items": { + "type": "string", + "pattern": "^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$" + } + } + ] + }, + "question": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "7a80a05d863e0772067cfc47a0c668443146ea610b0fa6e9f9d4ecc9c512b8d1" + }, + { + "definition": { + "name": "knowledge_mintlify_context", + "description": "Mintlify Index: research an implementation question across indexed product documentation and return a compact answer with primary-source citations.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "required": [ + "query" + ], + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + }, + "product": { + "type": "string", + "maxLength": 200 + }, + "includeDomains": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 300 + } + }, + "excludeDomains": { + "type": "array", + "maxItems": 100, + "items": { + "type": "string", + "maxLength": 300 + } + }, + "tokenBudget": { + "type": "integer", + "minimum": 500, + "maximum": 20000, + "default": 3000 + } + } + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "b3af73d28b72a634801352a766d0cd22bc2867f57c42e7a4766f774d2d7d2922" + }, + { + "definition": { + "name": "knowledge_skills_find", + "description": "Find relevant operator skills. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 5, + "default": 3 + }, + "mode": { + "type": "string", + "enum": [ + "fast", + "hybrid" + ], + "default": "hybrid" + }, + "min_confidence": { + "type": "string", + "enum": [ + "high" + ] + }, + "roots": { + "type": "array", + "minItems": 1, + "maxItems": 5, + "uniqueItems": true, + "items": { + "type": "string", + "enum": [ + "claude", + "claude-library", + "codex", + "agents", + "imported" + ] + } + } + }, + "required": [ + "query" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + } + }, + "digest": "c52bb053ab79f1bd902d2fee5a4464adfb9367bd3c2a44f3257a1bc0429990b6" + }, + { + "definition": { + "name": "knowledge_skills_get", + "description": "Load operator skill instructions or a referenced file. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "skill_id": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "path": { + "type": "string", + "minLength": 1, + "maxLength": 240 + } + }, + "required": [ + "skill_id" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + } + }, + "digest": "c2f14b25df76a3c426e1a549a5ee950047561e65c7ba32d67fca1a1f0fe3f7de" + }, + { + "definition": { + "name": "knowledge_skills_sync", + "description": "Sync operator skills; reject secrets per skill. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "skills": { + "type": "array", + "maxItems": 16, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "root", + "skill_id", + "name", + "description", + "files" + ], + "properties": { + "root": { + "type": "string", + "enum": [ + "claude", + "claude-library", + "codex", + "agents" + ] + }, + "skill_id": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "description": { + "type": "string", + "minLength": 1, + "maxLength": 2000 + }, + "files": { + "type": "array", + "minItems": 1, + "maxItems": 40, + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "path", + "sha256" + ], + "properties": { + "path": { + "type": "string", + "minLength": 1, + "maxLength": 240 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "content": { + "type": "string", + "maxLength": 262144 + }, + "content_base64": { + "type": "string", + "maxLength": 349528 + } + }, + "oneOf": [ + { + "required": [ + "content" + ] + }, + { + "required": [ + "content_base64" + ] + } + ] + } + } + } + } + }, + "delete": { + "type": "array", + "maxItems": 2000, + "uniqueItems": true, + "items": { + "type": "string", + "maxLength": 100, + "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$" + } + }, + "dry_run": { + "type": "boolean" + } + }, + "required": [ + "skills" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + } + }, + "digest": "ecf5ec49b5a712fd9fa0a76bfbeaebbb2115f8b1d5c72a45337a7830f35fc89d" + }, + { + "definition": { + "name": "knowledge_skills_discover", + "description": "Search the operator library plus public skill marketplaces (SkillsMP, skills.sh, ClawHub, SkillHub, claude-plugins.dev) and GitHub; sends query keywords to them. External results are untrusted. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "default": 10 + }, + "sources": { + "type": "array", + "minItems": 1, + "maxItems": 7, + "uniqueItems": true, + "items": { + "type": "string", + "enum": [ + "library", + "skillsmp", + "skills-sh", + "clawhub", + "skillhub", + "claude-plugins", + "github" + ] + } + } + }, + "required": [ + "query" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "15be6026cdeff75a3dad2386fc21770507030d1c3f570feae94b01efa35fb428" + }, + { + "definition": { + "name": "knowledge_skills_preview", + "description": "Read an external skill's SKILL.md as untrusted data with review flags; pass a discover result's preview object. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string", + "maxLength": 140, + "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$" + }, + "path": { + "type": "string", + "minLength": 1, + "maxLength": 240 + }, + "name": { + "type": "string", + "maxLength": 100, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$" + }, + "ref": { + "type": "string", + "maxLength": 100, + "pattern": "^[A-Za-z0-9._-]{1,100}$" + }, + "clawhub": { + "type": "string", + "maxLength": 201, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,99}/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$" + } + }, + "required": [] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "fe8decb6d4d952d1ec3eb93a60f7585dc565b2c31a0c561bb6f3a7c286be8dda" + }, + { + "definition": { + "name": "knowledge_skills_import", + "description": "Copy one external skill folder into the library's imported root, pinned to a GitHub commit or ClawHub version. Without commit/version it only returns a review plan; apply the plan's apply payload, plus accept_flags for each review flag, only after the operator approves. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "repository": { + "type": "string", + "maxLength": 140, + "pattern": "^[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$" + }, + "path": { + "type": "string", + "minLength": 1, + "maxLength": 240 + }, + "ref": { + "type": "string", + "maxLength": 100, + "pattern": "^[A-Za-z0-9._-]{1,100}$" + }, + "commit": { + "type": "string", + "pattern": "^[0-9a-f]{40}$" + }, + "clawhub": { + "type": "string", + "maxLength": 201, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,99}/[A-Za-z0-9][A-Za-z0-9._-]{0,99}$" + }, + "version": { + "type": "string", + "maxLength": 64, + "pattern": "^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$" + }, + "accept_flags": { + "type": "array", + "uniqueItems": true, + "maxItems": 7, + "items": { + "type": "string", + "enum": [ + "pipe_to_shell", + "destructive_delete", + "credential_paths", + "encoded_execution", + "instruction_override", + "global_install", + "marketplace_suspicious" + ] + } + } + }, + "required": [] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "550f25de67db8256c30a90039286846da2f9304a1ced2c8cb1cb553dd1348fcf" + }, + { + "definition": { + "name": "knowledge_skills_report", + "description": "Operator reports: updates lists imported skills with upstream diffs found by the daily check (check=true checks now); gaps lists searches the library could not answer, with external candidates. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "kind": { + "type": "string", + "enum": [ + "updates", + "gaps" + ] + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "default": 20 + }, + "check": { + "type": "boolean" + } + }, + "required": [ + "kind" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "12ec777348731e83d9d07a27f1ddb7026b77c8585d4970e360514ea0769b0d65" + }, + { + "definition": { + "name": "knowledge_artifact", + "description": "Read a retained source snapshot and immutable citation manifest. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + } + }, + "required": [ + "id" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "206b5d2554e758b5eac9f96814de3509ef1bc39014804faf3605788d40319dd2" + }, + { + "definition": { + "name": "knowledge_status", + "description": "Inspect source, job, allowance and configuration status. Requires knowledge:manage; configuration is not a connectivity test.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": {}, + "required": [] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "d5ee827a74adaddf616c85d5ac408dcf92bf2b70be1bcbe9f3af91cbe2becbad" + }, + { + "definition": { + "name": "knowledge_product_sites_get", + "description": "Read learned, pinned and blocked documentation sites for a product. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "product": { + "type": "string", + "minLength": 1, + "maxLength": 100 + } + }, + "required": [ + "product" + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "11318a4a0098cecf80585145102976a7dcda4bb46e736c15b51f0547f95ece94" + }, + { + "definition": { + "name": "knowledge_product_sites_update", + "description": "Pin, unpin, block, unblock or rebuild a product's learned documentation sites from retained artifacts. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "product": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "pin": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string", + "maxLength": 253, + "pattern": "^(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}|(?:github\\.com|gitlab\\.com|bitbucket\\.org|raw\\.githubusercontent\\.com)/[a-z0-9][a-z0-9_.-]{0,99})$", + "description": "Lowercase public hostname or code-host owner, such as github.com/pallets." + } + }, + "unpin": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string", + "maxLength": 253, + "pattern": "^(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}|(?:github\\.com|gitlab\\.com|bitbucket\\.org|raw\\.githubusercontent\\.com)/[a-z0-9][a-z0-9_.-]{0,99})$", + "description": "Lowercase public hostname or code-host owner, such as github.com/pallets." + } + }, + "block": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string", + "maxLength": 253, + "pattern": "^(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}|(?:github\\.com|gitlab\\.com|bitbucket\\.org|raw\\.githubusercontent\\.com)/[a-z0-9][a-z0-9_.-]{0,99})$", + "description": "Lowercase public hostname or code-host owner, such as github.com/pallets." + } + }, + "unblock": { + "type": "array", + "maxItems": 64, + "uniqueItems": true, + "items": { + "type": "string", + "maxLength": 253, + "pattern": "^(?:(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}|(?:github\\.com|gitlab\\.com|bitbucket\\.org|raw\\.githubusercontent\\.com)/[a-z0-9][a-z0-9_.-]{0,99})$", + "description": "Lowercase public hostname or code-host owner, such as github.com/pallets." + } + }, + "note": { + "type": "string", + "maxLength": 500 + }, + "rebuild": { + "type": "boolean" + } + }, + "required": [ + "product" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "73878951ae517ba5e612dc4a4d0fe28c52701cce5dd6142710d39e7e0224a998" + }, + { + "definition": { + "name": "knowledge_memos_stats", + "description": "Inspect verified answer memo counts, hits and ages by product. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": {}, + "required": [] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": true + } + }, + "digest": "efbbe203583c23d60525424ce3364307a0741f344212ebd2641fcdcbe65b5efe" + }, + { + "definition": { + "name": "knowledge_memos_purge", + "description": "Purge verified answer memos for a product or explicitly all products. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "product": { + "type": "string", + "maxLength": 100 + }, + "all": { + "type": "boolean" + } + }, + "required": [] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "f5e1b902e599628666a48c868bf0104332e5f54badc6a2b291b23befb8d18b60" + }, + { + "definition": { + "name": "knowledge_source_register", + "description": "Register an approved public documentation URL without fetching it. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "url": { + "type": "string", + "maxLength": 2048 + }, + "title": { + "type": "string", + "maxLength": 200 + }, + "product": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "version": { + "type": "string", + "maxLength": 80 + }, + "provider": { + "type": "string", + "enum": [ + "firecrawl", + "exa" + ], + "default": "firecrawl" + }, + "refresh_hours": { + "type": "integer", + "minimum": 1, + "maximum": 720, + "default": 24 + }, + "pinned": { + "type": "boolean" + } + }, + "required": [ + "url", + "product" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "205dd072d35d9b31f0be5392cfaaeb0bad01eb098a707f5cdc58002ab8c00a75" + }, + { + "definition": { + "name": "knowledge_source_update", + "description": "Enable, disable, pin or change a source refresh interval using its current revision. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + }, + "expected_revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740990 + }, + "enabled": { + "type": "boolean" + }, + "pinned": { + "type": "boolean" + }, + "refresh_hours": { + "type": "integer", + "minimum": 1, + "maximum": 720 + } + }, + "required": [ + "id", + "expected_revision" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "ea938fe39c30f126244ec7ddc93965ee2ebda1a8de05118683cde44ffa44f64d" + }, + { + "definition": { + "name": "knowledge_source_refresh", + "description": "Start or reconcile the source's durable indexing job. Can spend provider and platform allowances. Reuse the existing source after uncertainty. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + } + }, + "required": [ + "id" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "e405030e39b5e65ab34f8a004926ce12667262cf02201b410d718d8d91e8ff47" + }, + { + "definition": { + "name": "knowledge_job_cancel", + "description": "Fence future job work. Accepted upstream work and charges may still complete. Requires knowledge:manage.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + } + }, + "required": [ + "id" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "a02cb28ed0ba344f4090c342177eb95d6667833c1258faef621142b9d5afaefa" + }, + { + "definition": { + "name": "knowledge_policy_update", + "description": "Save the complete allowance and retention policy with its current revision. Requires knowledge:manage. Obtain operator confirmation of billing controls and retention rights; never invent acknowledgements or raise limits to retry unknown work.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "expected_revision": { + "type": "integer", + "minimum": 1, + "maximum": 9007199254740990 + }, + "enabled": { + "type": "boolean" + }, + "product_sites_mode": { + "type": "string", + "enum": [ + "off", + "observe", + "enforce" + ], + "default": "observe" + }, + "cache_ttl_seconds": { + "type": "integer", + "minimum": 0, + "maximum": 3600 + }, + "memo_exact": { + "type": "string", + "enum": [ + "on", + "off" + ], + "default": "on" + }, + "memo_semantic": { + "type": "string", + "enum": [ + "off", + "observe", + "on" + ], + "default": "observe" + }, + "memo_similarity": { + "type": "number", + "minimum": 0.85, + "maximum": 0.99, + "default": 0.92 + }, + "memo_ttl_hours": { + "type": "integer", + "minimum": 1, + "maximum": 720, + "default": 72 + }, + "retention_hours": { + "type": "integer", + "minimum": 1, + "maximum": 720 + }, + "unreviewed_retention_hours": { + "type": "integer", + "minimum": 1, + "maximum": 720, + "default": 24, + "description": "Retention for discoveries from hosts that only * admits." + }, + "allowed_hosts": { + "type": "array", + "minItems": 1, + "maxItems": 100, + "uniqueItems": true, + "items": { + "type": "string" + } + }, + "providers": { + "type": "object", + "additionalProperties": false, + "required": [ + "context7", + "firecrawl", + "exa", + "mintlify", + "deepwiki", + "ai_search", + "alexandria" + ], + "properties": { + "context7": { + "type": "object", + "additionalProperties": false, + "required": [ + "enabled", + "limit", + "background_limit", + "interactive_reserve", + "units_per_call", + "hard_limit_confirmed", + "retention_allowed" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "hard_limit_confirmed": { + "type": "boolean" + }, + "retention_allowed": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "background_limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "interactive_reserve": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "units_per_call": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + } + } + }, + "firecrawl": { + "type": "object", + "additionalProperties": false, + "required": [ + "enabled", + "limit", + "background_limit", + "interactive_reserve", + "units_per_call", + "hard_limit_confirmed", + "retention_allowed" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "hard_limit_confirmed": { + "type": "boolean" + }, + "retention_allowed": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "background_limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "interactive_reserve": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "units_per_call": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + } + } + }, + "exa": { + "type": "object", + "additionalProperties": false, + "required": [ + "enabled", + "limit", + "background_limit", + "interactive_reserve", + "units_per_call", + "hard_limit_confirmed", + "retention_allowed" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "hard_limit_confirmed": { + "type": "boolean" + }, + "retention_allowed": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "background_limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "interactive_reserve": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "units_per_call": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + } + } + }, + "mintlify": { + "type": "object", + "additionalProperties": false, + "required": [ + "enabled", + "limit", + "background_limit", + "interactive_reserve", + "units_per_call", + "hard_limit_confirmed", + "retention_allowed" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "hard_limit_confirmed": { + "type": "boolean" + }, + "retention_allowed": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "background_limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "interactive_reserve": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "units_per_call": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + } + } + }, + "deepwiki": { + "type": "object", + "additionalProperties": false, + "required": [ + "enabled", + "limit", + "background_limit", + "interactive_reserve", + "units_per_call", + "hard_limit_confirmed", + "retention_allowed" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "hard_limit_confirmed": { + "type": "boolean" + }, + "retention_allowed": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "background_limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "interactive_reserve": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "units_per_call": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + } + } + }, + "ai_search": { + "type": "object", + "additionalProperties": false, + "required": [ + "enabled", + "limit", + "background_limit", + "interactive_reserve", + "units_per_call", + "hard_limit_confirmed", + "retention_allowed" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "hard_limit_confirmed": { + "type": "boolean" + }, + "retention_allowed": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "background_limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "interactive_reserve": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "units_per_call": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + } + } + }, + "alexandria": { + "type": "object", + "additionalProperties": false, + "required": [ + "enabled", + "limit", + "background_limit", + "interactive_reserve", + "units_per_call", + "hard_limit_confirmed", + "retention_allowed" + ], + "properties": { + "enabled": { + "type": "boolean" + }, + "hard_limit_confirmed": { + "type": "boolean" + }, + "retention_allowed": { + "type": "boolean" + }, + "limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "background_limit": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "interactive_reserve": { + "type": "integer", + "minimum": 0, + "maximum": 100000 + }, + "units_per_call": { + "type": "integer", + "minimum": 1, + "maximum": 100000 + } + } + } + } + } + }, + "required": [ + "expected_revision", + "enabled", + "cache_ttl_seconds", + "retention_hours", + "allowed_hosts", + "providers" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": true + } + }, + "digest": "d4929050d917451d064691841bef156c141c1c4ae743910cf7c066e8763d7b88" + }, + { + "definition": { + "name": "knowledge_handoff_save", + "description": "Save an operator handoff for this principal; rejects secrets and records over 32 KB. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "project": { + "type": "string", + "maxLength": 200, + "minLength": 1, + "description": "owner/name from the git origin URL (for example acme/widgets), otherwise the directory name" + }, + "branch": { + "type": "string", + "maxLength": 200, + "description": "current git branch (git branch --show-current)" + }, + "title": { + "type": "string", + "maxLength": 200 + }, + "summary": { + "type": "string", + "maxLength": 4000 + }, + "sections": { + "type": "object", + "additionalProperties": false, + "properties": { + "goal": { + "type": "string", + "maxLength": 500 + }, + "state": { + "type": "string", + "maxLength": 500 + }, + "files": { + "type": "array", + "maxItems": 100, + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "path": { + "type": "string", + "maxLength": 500 + }, + "change": { + "type": "string", + "maxLength": 500 + } + }, + "required": [ + "path", + "change" + ] + } + }, + "commands": { + "type": "array", + "maxItems": 30, + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "command": { + "type": "string", + "maxLength": 500 + }, + "outcome": { + "type": "string", + "maxLength": 500 + } + }, + "required": [ + "command", + "outcome" + ] + } + }, + "decisions": { + "type": "array", + "maxItems": 30, + "items": { + "type": "string", + "maxLength": 500 + } + }, + "failed_attempts": { + "type": "array", + "maxItems": 30, + "items": { + "type": "string", + "maxLength": 500 + } + }, + "next_steps": { + "type": "array", + "maxItems": 30, + "items": { + "type": "string", + "maxLength": 500 + } + }, + "open_questions": { + "type": "array", + "maxItems": 20, + "items": { + "type": "string", + "maxLength": 500 + } + } + }, + "required": [] + }, + "source": { + "type": "object", + "additionalProperties": false, + "properties": { + "agent": { + "type": "string", + "enum": [ + "claude", + "codex", + "opencode", + "other" + ] + }, + "thread_id": { + "type": "string", + "maxLength": 200 + } + }, + "required": [ + "agent" + ] + }, + "ttl_days": { + "type": "integer", + "minimum": 1, + "maximum": 90, + "default": 14 + } + }, + "required": [ + "project", + "title", + "sections", + "source" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + } + }, + "digest": "d23a953d9d2412ba80852232109d5674943deee348969b1a789d6f0d979cec1d" + }, + { + "definition": { + "name": "knowledge_handoff_get", + "description": "Load the newest unexpired project/branch handoff with project fallback, or by id (optional project must match). Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "project": { + "type": "string", + "maxLength": 200, + "minLength": 1, + "description": "owner/name from the git origin URL (for example acme/widgets), otherwise the directory name" + }, + "branch": { + "type": "string", + "maxLength": 200, + "description": "current git branch (git branch --show-current)" + }, + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + } + }, + "required": [], + "anyOf": [ + { + "required": [ + "project" + ] + }, + { + "required": [ + "id" + ] + } + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + } + }, + "digest": "b58f7f9e1230012b72ca7e968cfcc469fd57329efb8e2128d99814e38b4f0449" + }, + { + "definition": { + "name": "knowledge_handoff_list", + "description": "List up to 20 unexpired handoffs belonging to this principal. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "project": { + "type": "string", + "maxLength": 200, + "minLength": 1, + "description": "owner/name from the git origin URL (for example acme/widgets), otherwise the directory name" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "default": 20 + } + }, + "required": [] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + } + }, + "digest": "72e3906b726fd92a1e095b031f4022c15f9ce07c7fb099e294cb865c60f43947" + }, + { + "definition": { + "name": "knowledge_handoff_delete", + "description": "Delete this principal’s handoff by id. Requires knowledge:read.", + "inputSchema": { + "type": "object", + "additionalProperties": false, + "properties": { + "id": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,80}$" + } + }, + "required": [ + "id" + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false, + "destructiveHint": true + } + }, + "digest": "afad004267bc98715d2715e80fbfe4c73973de604fe4fbb0a6ea7a4e8b0c38e3" + } + ] +} diff --git a/docs/mcp-contract-drift.md b/docs/mcp-contract-drift.md new file mode 100644 index 00000000..ae891956 --- /dev/null +++ b/docs/mcp-contract-drift.md @@ -0,0 +1,106 @@ +# MCP schema compatibility digests + +`MCP_CONTRACT_DIGESTS_ENABLED` defaults to false. Empty, `false`, and `0` disable it; +`true` and `1` enable it (case-insensitive, surrounding whitespace ignored). A malformed +value disables it and logs one warning per process or isolate, without the value. + +When disabled, discovery and tool calls retain their existing output and a supplied +`X-MultiLLM-MCP-Contract` header is ignored. When enabled, discovery adds +`_meta.contract_digest` to each visible tool and to the tools/list result. The result +digest covers only tools authorized for that caller and selected toolsets. Filtering +and discovery order stay the same. Tool digests cover name, complete input/output +schemas, and contract version `1.0.0`; descriptions and annotations outside schemas +are excluded. Missing outputSchema is represented as null. + +An enabled client may pin the **individual tool** digest with: + +```http +X-MultiLLM-MCP-Contract: <64 lowercase hexadecimal characters from tool._meta.contract_digest> +``` + +The catalogue digest is for comparing discovery sets, not for pinning an individual +call. After authentication and tool authorization, a mismatch (including a malformed +or empty supplied pin) returns HTTP 409 with error code `mcp_contract_mismatch` +and message `The pinned MCP tool contract has changed. Refresh discovery.` before +execution, tool storage lookup, metering or provider dispatch. Unpinned calls keep working +when schemas change. No automatic retry is introduced. With the flag disabled, even +an invalid pin is ignored. A matching pin authorizes no additional permissions. + +## Registered HTTP paths + +Both the Flask gateway and the public edge Worker serve `POST /mcp`. Their +`tools/list` results include digests when enabled. `/mcp?toolsets=core,exa` restricts +discovery before hashing. Each tool includes `_meta.contract_digest`, and the +result includes `_meta.contract_digest` over its visible tools. Administrator, +reader and manager discovery follows the existing authorization rules. + +`tools/call` checks the pin against the same contract used by discovery, after +authentication and tool authorization and before dispatch. A rejected pin returns +this JSON-RPC error with HTTP status 409 and `Cache-Control: no-store`: + +```json +{"jsonrpc":"2.0","id":7,"error":{"code":"mcp_contract_mismatch","message":"The pinned MCP tool contract has changed. Refresh discovery."}} +``` + +The check covers every public Knowledge tool, including native provider tools and +tools forwarded to the private Knowledge service. Unauthorized calls keep the +existing scope-denial response and never expose a digest. Disabled calls keep +existing response bytes, status codes, headers and private dispatch payloads. +REST paths do not interpret this pin header. Status outputs report existing +operation names and native hash checks; they do not list tool schema definitions. +The offline catalogue and baseline remain independent of the runtime flag. + +Set `MCP_CONTRACT_DIGESTS_ENABLED=true` on the public edge, Flask Container and +private Knowledge Worker consistently. The Container environment allowlist must +forward this key. Native Worker dispatch also checks an explicitly supplied +`options.contractPin` before authority, storage, metering and provider calls. +There are no new routes, response headers, migrations or runtime middleware hooks. + +## Canonical format and bounds + +`multillm-mcp-contract-v1` hashes UTF-8 compact JSON of typed nodes. Null is +`["null"]`, booleans and strings are `[type,value]`, arrays are `["array",nodes]`, +and objects are `["object",[[key,node],...]]` sorted by Unicode scalar key order. +Numbers use `["number",hex]`, where hex is the exact big-endian IEEE-754 binary64 +representation. Equal integer/float values hash identically; negative zero becomes +positive zero. Tags prevent collisions between numbers and schema strings. Unknown +schema keywords remain intact and all arrays retain their order. This is a versioned +local canonical format, not RFC 8785. Changing the format requires new baselines. + +Numbers must be finite with absolute value at most `2**53-1`; strings must contain +Unicode scalar values. Each canonical value is limited to 256 KiB, 64 nested levels, +and 65,536 nodes. These are bounds on trusted tool schemas and offline inputs, not +new limits on tool argument payloads. No hashing happens for disabled or unpinned +preflight. A digest identifies a declared schema, not a provider capability or a +promise that a provider result conforms to an output schema. + +## Offline baseline and diff + +From the repository root, using the installed Python environment: + +```sh +python scripts/build_knowledge_mcp_catalogue.py --baseline docs/mcp-contract-baseline.json +python scripts/build_knowledge_mcp_catalogue.py --diff docs/mcp-contract-baseline.json +``` + +Both modes use local tool definitions and perform no network calls. The baseline +contains declared schemas, digests, and shared Python/Worker canonical vectors with +no timestamp, prompts, responses or credentials. Repeating a build yields identical +bytes. These modes do not regenerate `worker/knowledge-mcp-catalogue.json`; that +catalogue can be regenerated separately after tool schema changes. The existing +`--check` and no-argument catalogue build retain their prior behavior. + +Diff output lists paths, change kinds and a combined classification. Tool/property +removal, required-field addition and type narrowing are breaking. Optional input +property additions and type widening are compatible. Unknown keyword changes, +constraint/composition/reference changes, output schema additions, version changes, +and ambiguous changes require review. Compatibility is a conservative structural +report, not a full JSON Schema implication proof. Tool renames appear as removal +plus addition. Existing schema fields remain in the digest even if the classifier +cannot interpret them. Baseline input is limited to 4 MiB. CLI exit status is 0 for +compatible, 1 for breaking/review-required, and 2 for an invalid baseline or operation. + +This feature invokes no providers, spends no credits, stores no request content, +and adds no retention policy. Offline files contain public contract declarations; +protect them as source artifacts rather than request logs. Enabling the flag does +not change existing allowances, authentication, caching or retry permission. diff --git a/package.json b/package.json index 42ee5f27..fdfcbff8 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "lint": "ruff check . --select E9,F63,F7,F82", "typecheck": "mypy --ignore-missing-imports --follow-imports=skip --disable-error-code import-untyped --disable-error-code var-annotated --disable-error-code arg-type --disable-error-code assignment --disable-error-code operator app.py routes services providers streaming", "test": "python -m pytest -q", - "test:worker": "node --test tests/test_cloudflare_worker.mjs tests/test_cascades_worker.mjs tests/test_cascades_dashboard.mjs tests/test_image_quality_worker.mjs tests/test_secret_scan_worker.mjs tests/test_secret_firewall_worker.mjs tests/test_secret_firewall_coverage_worker.mjs tests/test_roleplay_compaction_budget_worker.mjs tests/test_roleplay_compaction_model_worker.mjs tests/test_roleplay_stream_validation_worker.mjs tests/test_aihubmix_worker.mjs tests/test_gpt_image_moderation_worker.mjs tests/test_dashboard_scripts.mjs tests/test_operations_dashboard.mjs tests/test_opencode_reasoning_worker.mjs tests/test_opencode_thinking_worker.mjs tests/test_nanogpt_reasoning_worker.mjs tests/test_nanogpt_speed_routing_worker.mjs tests/test_sse_heartbeat_worker.mjs tests/test_roleplay_worker.mjs tests/test_roleplay_config_worker.mjs tests/test_roleplay_glm_failover_worker.mjs tests/test_roleplay_intelligence_worker.mjs tests/test_roleplay_memory_worker.mjs tests/test_roleplay_compatibility_worker.mjs tests/test_roleplay_history_reconciliation_worker.mjs tests/test_roleplay_output_contract_analysis.mjs tests/test_roleplay_output_contract_cleanup_worker.mjs tests/test_roleplay_output_contract_nonstream_worker.mjs tests/test_roleplay_output_contract_worker.mjs tests/test_roleplay_performance_worker.mjs tests/test_roleplay_quality_routing_worker.mjs tests/test_roleplay_reasoning_worker.mjs tests/test_roleplay_session_storage_worker.mjs tests/test_roleplay_transport_failure_worker.mjs tests/test_roleplay_unlimited_worker.mjs tests/test_roleplay_workbench_worker.mjs tests/test_roleplay_candidate_context_worker.mjs tests/test_roleplay_operator_worker.mjs tests/test_workbench_stream.mjs tests/test_intelligence_worker.mjs tests/test_intelligence_d1_worker.mjs tests/test_intelligence_auth_worker.mjs tests/test_intelligence_outbound_worker.mjs tests/test_intelligence_operator.mjs tests/test_control_users_worker.mjs tests/test_control_audit_worker.mjs tests/test_access_sso_worker.mjs tests/test_d1_schema_worker.mjs tests/test_shadow_eval_worker.mjs tests/test_auto_routes_worker.mjs tests/test_ai_outbound_worker.mjs tests/test_knowledge_*.mjs tests/test_control_state_worker.mjs tests/test_route_health_worker.mjs tests/test_gateway_mcp_worker.mjs tests/test_usage_ledger_worker.mjs tests/test_media_outbound_worker.mjs tests/test_media_files_worker.mjs tests/test_media_jobs_worker.mjs tests/test_tool_repair_worker.mjs tests/test_prometheus_worker.mjs tests/test_evaluation_noise_floor_worker.mjs tests/test_prompt_templates_worker.mjs tests/test_config_snapshots_worker.mjs", + "test:worker": "node --test tests/test_cloudflare_worker.mjs tests/test_cascades_worker.mjs tests/test_cascades_dashboard.mjs tests/test_image_quality_worker.mjs tests/test_secret_scan_worker.mjs tests/test_secret_firewall_worker.mjs tests/test_secret_firewall_coverage_worker.mjs tests/test_roleplay_compaction_budget_worker.mjs tests/test_roleplay_compaction_model_worker.mjs tests/test_roleplay_stream_validation_worker.mjs tests/test_aihubmix_worker.mjs tests/test_gpt_image_moderation_worker.mjs tests/test_dashboard_scripts.mjs tests/test_operations_dashboard.mjs tests/test_opencode_reasoning_worker.mjs tests/test_opencode_thinking_worker.mjs tests/test_nanogpt_reasoning_worker.mjs tests/test_nanogpt_speed_routing_worker.mjs tests/test_sse_heartbeat_worker.mjs tests/test_roleplay_worker.mjs tests/test_roleplay_config_worker.mjs tests/test_roleplay_glm_failover_worker.mjs tests/test_roleplay_intelligence_worker.mjs tests/test_roleplay_memory_worker.mjs tests/test_roleplay_compatibility_worker.mjs tests/test_roleplay_history_reconciliation_worker.mjs tests/test_roleplay_output_contract_analysis.mjs tests/test_roleplay_output_contract_cleanup_worker.mjs tests/test_roleplay_output_contract_nonstream_worker.mjs tests/test_roleplay_output_contract_worker.mjs tests/test_roleplay_performance_worker.mjs tests/test_roleplay_quality_routing_worker.mjs tests/test_roleplay_reasoning_worker.mjs tests/test_roleplay_session_storage_worker.mjs tests/test_roleplay_transport_failure_worker.mjs tests/test_roleplay_unlimited_worker.mjs tests/test_roleplay_workbench_worker.mjs tests/test_roleplay_candidate_context_worker.mjs tests/test_roleplay_operator_worker.mjs tests/test_workbench_stream.mjs tests/test_intelligence_worker.mjs tests/test_intelligence_d1_worker.mjs tests/test_intelligence_auth_worker.mjs tests/test_intelligence_outbound_worker.mjs tests/test_intelligence_operator.mjs tests/test_control_users_worker.mjs tests/test_control_audit_worker.mjs tests/test_access_sso_worker.mjs tests/test_d1_schema_worker.mjs tests/test_shadow_eval_worker.mjs tests/test_auto_routes_worker.mjs tests/test_ai_outbound_worker.mjs tests/test_knowledge_*.mjs tests/test_control_state_worker.mjs tests/test_route_health_worker.mjs tests/test_gateway_mcp_worker.mjs tests/test_usage_ledger_worker.mjs tests/test_media_outbound_worker.mjs tests/test_media_files_worker.mjs tests/test_media_jobs_worker.mjs tests/test_tool_repair_worker.mjs tests/test_prometheus_worker.mjs tests/test_evaluation_noise_floor_worker.mjs tests/test_prompt_templates_worker.mjs tests/test_config_snapshots_worker.mjs tests/test_mcp_contract_drift_worker.mjs", "db:migrate": "python scripts/validate_sqlite_schema.py --apply", "db:validate": "python scripts/validate_sqlite_schema.py", "security:secrets": "python scripts/check_static_secrets.py", diff --git a/routes/knowledge.py b/routes/knowledge.py index f8010b35..a9c5bfbb 100644 --- a/routes/knowledge.py +++ b/routes/knowledge.py @@ -191,6 +191,10 @@ def _mcp_tool(identifier, params): return _rpc_result(identifier, {"isError": True, "content": [{"type": "text", "text": json.dumps({ "error": {"code": "insufficient_scope", "message": "The key is not authorized for this Knowledge tool."}, })}]}) + try: + mcp.check_contract_pin(tool_name, request.headers.get("X-MultiLLM-MCP-Contract"), definition=entry["definition"]) + except KnowledgeError as error: + return _rpc_error(identifier, error.code, error.message, error.status) arguments = params.get("arguments", {}) if not isinstance(arguments, dict): return _rpc_error(identifier, -32602, "Tool arguments must be an object.") @@ -256,9 +260,8 @@ def _mcp(): toolsets = mcp.requested_toolsets(request.args.get("toolsets")) except ValueError: return _rpc_error(identifier, -32602, f"Unknown toolset. Use any of: {', '.join(mcp.TOOLSETS)}.") - return _rpc_result(identifier, {"tools": [entry["definition"] for entry in _CATALOGUE["tools"] - if management.permits(g.authenticated_user, entry["scope"]) - and (toolsets is None or entry["toolset"] in toolsets)]}) + return _rpc_result(identifier, mcp.discovery_for_user( + g.authenticated_user, toolsets, entries=_CATALOGUE["tools"])) if method != "tools/call": return _rpc_error(identifier, -32601, "Method not found.") return _mcp_tool(identifier, params) diff --git a/routes/knowledge_mcp.py b/routes/knowledge_mcp.py index dcbba2d0..5924a6c9 100644 --- a/routes/knowledge_mcp.py +++ b/routes/knowledge_mcp.py @@ -13,6 +13,7 @@ from routes import knowledge_handoffs as handoffs from routes import knowledge_skills as skills from services.knowledge_native import NATIVE_OPERATIONS, NATIVE_TOOLS +from services import mcp_contract_drift as drift CATALOGUE_PATH = Path(__file__).resolve().parents[1] / "worker" / "knowledge-mcp-catalogue.json" # 2025-03-26 is not offered: it requires JSON-RPC batching, which this server does not accept. @@ -130,3 +131,27 @@ def catalogue(): def catalogue_json(): return json.dumps(catalogue(), indent=2, ensure_ascii=False) + "\n" + + +def discovery_contract(scopes, toolsets=None, *, enabled=None, entries=None): + """Runtime discovery hook: authorization filtering precedes digest metadata.""" + active = drift.digests_enabled() if enabled is None else enabled + return drift.discovery_contract(catalogue()["tools"] if entries is None else entries, scopes, toolsets, enabled=active) + + +def discovery_for_user(user, toolsets=None, *, entries=None): + scopes = ["admin"] if user.get("is_admin") else user.get("scopes") or [] + return discovery_contract(scopes, toolsets, entries=entries) + + +def check_contract_pin(tool_name, pin, *, enabled=None, definition=None): + """Runtime preflight hook; invoke after tool authorization, before dispatch.""" + active = drift.digests_enabled() if enabled is None else enabled + if not active or pin is None: + return + if definition is None: + definition = next((entry["definition"] for entry in catalogue()["tools"] + if entry["definition"]["name"] == tool_name), None) + if definition is None: + raise ValueError("Unknown Knowledge tool.") + drift.check_contract_pin(definition, pin, enabled=True) diff --git a/scripts/build_knowledge_mcp_catalogue.py b/scripts/build_knowledge_mcp_catalogue.py index 4f068230..7c043404 100644 --- a/scripts/build_knowledge_mcp_catalogue.py +++ b/scripts/build_knowledge_mcp_catalogue.py @@ -1,14 +1,39 @@ """Write the edge Worker's copy of the Knowledge MCP catalogue; --check only verifies it.""" +import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from routes.knowledge_mcp import CATALOGUE_PATH, catalogue_json +from routes.knowledge_mcp import CATALOGUE_PATH, catalogue, catalogue_json +from services.mcp_contract_drift import CONTRACT_VERSION, FORMAT, baseline_json, diff_contracts def main(argv): + if len(argv) == 2 and argv[0] in {"--baseline", "--diff"}: + path = Path(argv[1]).resolve() + if path == CATALOGUE_PATH.resolve(): + print("Contract baseline operations cannot overwrite the Worker catalogue.", file=sys.stderr) + return 2 + definitions = [entry["definition"] for entry in catalogue()["tools"]] + try: + if argv[0] == "--baseline": + path.write_text(baseline_json(definitions), encoding="utf-8") + return 0 + if path.stat().st_size > 4 * 1024 * 1024: + raise ValueError("Contract baseline exceeds the 4 MiB limit.") + previous = json.loads(path.read_text(encoding="utf-8")) + if (not isinstance(previous, dict) or previous.get("format") != FORMAT + or not isinstance(previous.get("tools"), list)): + raise ValueError("Unsupported contract baseline format.") + report = diff_contracts([entry["definition"] for entry in previous["tools"]], definitions, + old_version=previous.get("contract_version"), new_version=CONTRACT_VERSION) + except (OSError, ValueError, KeyError, TypeError) as error: + print(f"Contract baseline operation failed: {type(error).__name__}.", file=sys.stderr) + return 2 + print(json.dumps(report, indent=2, ensure_ascii=False)) + return 0 if report["classification"] == "compatible" else 1 expected = catalogue_json() if argv == ["--check"]: current = CATALOGUE_PATH.read_text(encoding="utf-8") if CATALOGUE_PATH.exists() else None @@ -18,7 +43,7 @@ def main(argv): return 1 return 0 if argv: - print("Usage: python scripts/build_knowledge_mcp_catalogue.py [--check]", file=sys.stderr) + print("Usage: python scripts/build_knowledge_mcp_catalogue.py [--check | --baseline PATH | --diff PATH]", file=sys.stderr) return 2 CATALOGUE_PATH.write_text(expected, encoding="utf-8") return 0 diff --git a/services/mcp_contract_drift.py b/services/mcp_contract_drift.py new file mode 100644 index 00000000..56ec6f5a --- /dev/null +++ b/services/mcp_contract_drift.py @@ -0,0 +1,213 @@ +"""Bounded, offline MCP schema digests and conservative compatibility reports.""" + +import hashlib +import json +import logging +import math +import os +import struct + +from services.knowledge_client import KnowledgeError + +CONTRACT_VERSION = "1.0.0" +FORMAT = "multillm-mcp-contract-v1" +MAX_CANONICAL_BYTES = 256 * 1024 +MAX_DEPTH = 64 +MAX_NODES = 65536 +_warned = False + + +def digests_enabled(value=None): + """Empty or malformed configuration cannot change existing traffic.""" + global _warned + if value is None: + value = os.environ.get("MCP_CONTRACT_DIGESTS_ENABLED", "") + if isinstance(value, bool): + return value + if isinstance(value, str): + normalized = value.strip().lower() + if normalized in ("", "false", "0"): + return False + if normalized in ("true", "1"): + return True + if not _warned: + logging.getLogger(__name__).warning("Invalid MCP_CONTRACT_DIGESTS_ENABLED; contract digests are disabled.") + _warned = True + return False + + +def canonical_value(value): + """Typed JSON nodes with Unicode-scalar key ordering and binary64 numbers. + + Tagged nodes avoid collisions with schema strings. Numeric equality uses the + exact finite binary64 representation in both runtimes, including integer/float + equivalence and normalized negative zero. No schema keyword is discarded. + """ + remaining = MAX_NODES + + def text(value): + if any(0xD800 <= ord(char) <= 0xDFFF for char in value): + raise ValueError("Contract strings must contain Unicode scalar values.") + return value + + def node(item, depth): + nonlocal remaining + remaining -= 1 + if depth > MAX_DEPTH or remaining < 0: + raise ValueError("Contract exceeds canonical depth or node limits.") + if item is None: + return ["null"] + if isinstance(item, bool): + return ["boolean", item] + if isinstance(item, (int, float)): + if abs(item) > 2**53 - 1 or not math.isfinite(item): + raise ValueError("Contract numbers must be finite and within the interoperable range.") + return ["number", struct.pack(">d", float(item) if item else 0.0).hex()] + if isinstance(item, str): + return ["string", text(item)] + if isinstance(item, list): + return ["array", [node(child, depth + 1) for child in item]] + if isinstance(item, dict) and all(isinstance(key, str) for key in item): + return ["object", [[text(key), node(item[key], depth + 1)] for key in sorted(item)]] + raise ValueError("Contract contains a non-JSON value.") + + encoded = json.dumps(node(value, 0), ensure_ascii=False, separators=(",", ":")) + if len(encoded.encode("utf-8")) > MAX_CANONICAL_BYTES: + raise ValueError("Contract exceeds canonical byte limit.") + return encoded + + +def contract_payload(definition, contract_version=CONTRACT_VERSION): + if not isinstance(definition, dict) or not isinstance(definition.get("name"), str) or "inputSchema" not in definition: + raise ValueError("A tool contract requires a name and inputSchema.") + return {"name": definition["name"], "inputSchema": definition["inputSchema"], + "outputSchema": definition.get("outputSchema"), "contractVersion": contract_version} + + +def canonical_contract(definition, contract_version=CONTRACT_VERSION): + return canonical_value(contract_payload(definition, contract_version)) + + +def contract_digest(definition, contract_version=CONTRACT_VERSION): + return hashlib.sha256(canonical_contract(definition, contract_version).encode("utf-8")).hexdigest() + + +def catalogue_digest(definitions, contract_version=CONTRACT_VERSION): + contracts = [contract_payload(tool, contract_version) for tool in sorted(definitions, key=lambda tool: tool["name"])] + return hashlib.sha256(canonical_value(contracts).encode("utf-8")).hexdigest() + + +def discovery_contract(entries, scopes, toolsets=None, *, enabled=False): + """Filter before hashing so unauthorized tools cannot affect visible digests.""" + tools = [entry["definition"] for entry in entries + if ("admin" in scopes or entry["scope"] in scopes) + and (toolsets is None or entry["toolset"] in toolsets)] + if not enabled: + return {"tools": tools} + return {"tools": [{**tool, "_meta": {**tool.get("_meta", {}), "contract_digest": contract_digest(tool)}} for tool in tools], + "_meta": {"contract_digest": catalogue_digest(tools)}} + + +def check_contract_pin(definition, pin, *, enabled=False): + """Call after authorization and before dispatch; no hash work without a pin.""" + if not enabled or pin is None: + return + if not isinstance(pin, str) or len(pin) != 64 or pin != contract_digest(definition): + raise KnowledgeError("mcp_contract_mismatch", "The pinned MCP tool contract has changed. Refresh discovery.", 409) + + +def _type_set(value): + if value is None: + return {"null", "boolean", "object", "array", "number", "integer", "string"} + types = {value} if isinstance(value, str) else set(value) if isinstance(value, list) else set() + if "number" in types: + types.add("integer") + return types + + +def _schema_changes(old, new, path, changes, *, output=False): + if canonical_value(old) == canonical_value(new): + return + if not isinstance(old, dict) or not isinstance(new, dict): + grade = "breaking" if old is True and new is False else "review-required" + changes.append({"path": path, "kind": "schema_changed", "classification": grade}) + return + old_props, new_props = old.get("properties", {}), new.get("properties", {}) + if isinstance(old_props, dict) and isinstance(new_props, dict): + for name in sorted(old_props.keys() - new_props.keys()): + changes.append({"path": f"{path}/properties/{name}", "kind": "property_removed", "classification": "breaking"}) + for name in sorted(new_props.keys() - old_props.keys()): + grade = "breaking" if name in new.get("required", []) else "review-required" if output else "compatible" + changes.append({"path": f"{path}/properties/{name}", "kind": "property_added", "classification": grade}) + for name in sorted(old_props.keys() & new_props.keys()): + _schema_changes(old_props[name], new_props[name], f"{path}/properties/{name}", changes, output=output) + for key in sorted(old.keys() | new.keys()): + if key == "properties" and isinstance(old_props, dict) and isinstance(new_props, dict): + continue + if canonical_value(old.get(key)) == canonical_value(new.get(key)) and (key in old) == (key in new): + continue + grade, kind = "review-required", "keyword_changed" + if key == "required" and isinstance(old.get(key, []), list) and isinstance(new.get(key, []), list): + added = set(new.get(key, [])) - set(old.get(key, [])) + removed = set(old.get(key, [])) - set(new.get(key, [])) + grade = "breaking" if added else "compatible" if removed else "review-required" + kind = "required_changed" + elif key == "type": + before, after = _type_set(old.get(key)), _type_set(new.get(key)) + grade = "breaking" if before - after else "compatible" if after - before else "review-required" + kind = "type_changed" + if output and grade == "compatible": + grade = "review-required" + changes.append({"path": f"{path}/{key}", "kind": kind, "classification": grade}) + + +def diff_contracts(old, new, *, old_version=CONTRACT_VERSION, new_version=CONTRACT_VERSION): + """Unknown keyword/constraint changes require review; only proven additions pass.""" + before, after = _indexed(old), _indexed(new) + changes = [] + for name in sorted(before.keys() - after.keys()): + changes.append({"path": name, "kind": "tool_removed", "classification": "breaking"}) + for name in sorted(after.keys() - before.keys()): + changes.append({"path": name, "kind": "tool_added", "classification": "compatible"}) + for name in sorted(before.keys() & after.keys()): + _schema_changes(before[name]["inputSchema"], after[name]["inputSchema"], f"{name}/inputSchema", changes) + if canonical_value(before[name].get("outputSchema")) != canonical_value(after[name].get("outputSchema")): + if "outputSchema" in before[name] and "outputSchema" not in after[name]: + changes.append({"path": f"{name}/outputSchema", "kind": "output_schema_removed", "classification": "breaking"}) + elif "outputSchema" not in before[name]: + changes.append({"path": f"{name}/outputSchema", "kind": "output_schema_added", "classification": "review-required"}) + else: + _schema_changes(before[name]["outputSchema"], after[name]["outputSchema"], f"{name}/outputSchema", changes, output=True) + if old_version != new_version: + changes.append({"path": "contractVersion", "kind": "version_changed", "classification": "review-required"}) + grades = {change["classification"] for change in changes} + return {"classification": "breaking" if "breaking" in grades else "review-required" if "review-required" in grades else "compatible", + "changes": changes} + + +def _indexed(definitions): + result = {} + for tool in definitions: + contract_payload(tool) + if tool["name"] in result: + raise ValueError("Duplicate tool name in contract catalogue.") + result[tool["name"]] = tool + return result + + +VECTOR_DEFINITIONS = [ + {"name": "knowledge_test", "inputSchema": {"type": "object", "properties": { + "b": {"type": ["string", "null"]}, "a": {"minimum": 1.0, "x-vendor": {"東京": "café", "values": [True, None, -0.0, 1e-7]}}}, + "required": ["b", "a"]}, "outputSchema": {"type": "string"}}, + {"name": "knowledge_😀", "inputSchema": {"\ue000": 1, "😀": 2, "type": "object", "anyOf": [{"type": "string"}, {"type": "number"}]}}, + {"name": "knowledge_test", "inputSchema": True}, +] + + +def baseline_json(definitions): + _indexed(definitions) + baseline = {"format": FORMAT, "contract_version": CONTRACT_VERSION, + "vectors": [{"definition": tool, "contract_version": CONTRACT_VERSION, + "canonical": canonical_contract(tool), "digest": contract_digest(tool)} for tool in VECTOR_DEFINITIONS], + "tools": [{"definition": tool, "digest": contract_digest(tool)} for tool in definitions]} + return json.dumps(baseline, indent=2, ensure_ascii=False) + "\n" diff --git a/tests/fixtures/secret_firewall_coverage.json b/tests/fixtures/secret_firewall_coverage.json index ff0fe87b..faabfa76 100644 --- a/tests/fixtures/secret_firewall_coverage.json +++ b/tests/fixtures/secret_firewall_coverage.json @@ -244,6 +244,7 @@ "worker/knowledge/authority-client.mjs", "worker/knowledge/authority.mjs", "worker/knowledge/cache.mjs", + "worker/knowledge/contract-drift.mjs", "worker/knowledge/contracts.mjs", "worker/knowledge/corpus.mjs", "worker/knowledge/credentials.mjs", diff --git a/tests/test_mcp_contract_drift.py b/tests/test_mcp_contract_drift.py new file mode 100644 index 00000000..963ba82b --- /dev/null +++ b/tests/test_mcp_contract_drift.py @@ -0,0 +1,282 @@ +"""Offline contract checks use shared vectors and synthetic dispatch.""" +import copy +import json +from pathlib import Path +from unittest.mock import Mock + +import pytest + +from routes import knowledge_mcp +from services import mcp_contract_drift as drift +from services.knowledge_client import KnowledgeError +from scripts import build_knowledge_mcp_catalogue as build + +BASELINE = Path(__file__).resolve().parents[1] / "docs/mcp-contract-baseline.json" +TOOL = {"name": "knowledge_example", "inputSchema": {"type": "object", "properties": {"query": {"type": ["string", "null"]}}, "required": []}} + + +def test_shared_canonical_vectors_and_number_equivalence(): + for vector in json.loads(BASELINE.read_text())["vectors"]: + assert drift.canonical_contract(vector["definition"], vector["contract_version"]) == vector["canonical"] + assert drift.contract_digest(vector["definition"], vector["contract_version"]) == vector["digest"] + assert drift.canonical_value(1) == drift.canonical_value(1.0) + assert drift.canonical_value(0) == drift.canonical_value(-0.0) + + +def test_order_unknown_fields_and_array_order(): + changed = copy.deepcopy(TOOL) + changed["inputSchema"] = dict(reversed(list(changed["inputSchema"].items()))) + assert drift.contract_digest(TOOL) == drift.contract_digest(changed) + changed["inputSchema"]["x-vendor"] = {"opaque": [1, 2]} + assert drift.contract_digest(TOOL) != drift.contract_digest(changed) + first = drift.contract_digest(changed) + changed["inputSchema"]["x-vendor"]["opaque"].reverse() + assert first != drift.contract_digest(changed) + assert drift.contract_digest(TOOL, "2") != drift.contract_digest(TOOL) + + +@pytest.mark.parametrize("value", [float("nan"), float("inf"), 2**53, "\ud800"]) +def test_non_interoperable_values_rejected(value): + with pytest.raises(ValueError): + drift.canonical_value(value) + + +@pytest.mark.parametrize("change,classification", [ + (lambda s: s["properties"].update(optional={"type": "string"}), "compatible"), + (lambda s: s["required"].append("query"), "breaking"), + (lambda s: s["properties"]["query"].update(type="string"), "breaking"), + (lambda s: s["properties"].pop("query"), "breaking"), + (lambda s: s.update(**{"x-vendor": "new"}), "review-required"), + (lambda s: s.update(anyOf=[{"type": "string"}]), "review-required"), +]) +def test_diff_classification(change, classification): + changed = copy.deepcopy(TOOL) + change(changed["inputSchema"]) + report = drift.diff_contracts([TOOL], [changed]) + assert report["classification"] == classification + assert report["changes"] + + +def test_tool_removal_output_drift_and_unknown_changes_need_review(): + assert drift.diff_contracts([TOOL], [])["classification"] == "breaking" + changed = {**TOOL, "outputSchema": {"type": "string"}} + assert drift.diff_contracts([TOOL], [changed])["classification"] == "review-required" + assert drift.diff_contracts([TOOL], [TOOL])["classification"] == "compatible" + assert drift.diff_contracts([TOOL], [TOOL], old_version="1", new_version="2")["classification"] == "review-required" + + +@pytest.mark.parametrize("value", [None, "", "false", "0", "bad", " true-ish "]) +def test_flag_defaults_and_warns_without_values(value, caplog, monkeypatch): + monkeypatch.setattr(drift, "_warned", False) + assert not drift.digests_enabled(value) + if value and value not in ("false", "0"): + assert "MCP_CONTRACT_DIGESTS_ENABLED" in caplog.text + assert value not in caplog.text + caplog.clear() + assert not drift.digests_enabled(value) + assert not caplog.text + + +def test_default_catalogue_byte_equality_and_scope_filtered_discovery(monkeypatch): + monkeypatch.delenv("MCP_CONTRACT_DIGESTS_ENABLED", raising=False) + assert knowledge_mcp.catalogue_json() == knowledge_mcp.CATALOGUE_PATH.read_text() + reader = knowledge_mcp.discovery_contract(["knowledge:read"], {"core"}, enabled=True) + assert [t["name"] for t in reader["tools"]] == ["knowledge_context", "knowledge_search", "knowledge_artifact"] + assert reader["_meta"]["contract_digest"] == drift.catalogue_digest(reader["tools"]) + assert all("contract_digest" in t["_meta"] for t in reader["tools"]) + manager = knowledge_mcp.discovery_contract(["knowledge:manage"], enabled=True) + assert all(t["name"] not in {"knowledge_context", "knowledge_search"} for t in manager["tools"]) + assert manager["_meta"]["contract_digest"] != reader["_meta"]["contract_digest"] + plain = knowledge_mcp.discovery_contract(["knowledge:read"], {"core"}, enabled=False) + assert "_meta" not in plain and all("_meta" not in t for t in plain["tools"]) + + +def test_pin_guard_before_dispatch_with_off_and_unpinned_bypass(monkeypatch): + dispatch = Mock(return_value={"ok": True}) + name = "knowledge_context" + def call(pin): + knowledge_mcp.check_contract_pin(name, pin) + return dispatch() + monkeypatch.setenv("MCP_CONTRACT_DIGESTS_ENABLED", "true") + with pytest.raises(KnowledgeError) as caught: + call("0" * 64) + assert caught.value.code == "mcp_contract_mismatch" and caught.value.status == 409 + dispatch.assert_not_called() + tool = next(e["definition"] for e in knowledge_mcp.catalogue()["tools"] if e["definition"]["name"] == name) + call(drift.contract_digest(tool)) + call(None) + monkeypatch.setenv("MCP_CONTRACT_DIGESTS_ENABLED", "") + call("malformed-pin") + assert dispatch.call_count == 3 + + +def test_offline_baseline_deterministic_and_diff_does_not_write_catalogue(tmp_path, capsys): + original = knowledge_mcp.CATALOGUE_PATH.read_bytes() + path = tmp_path / "baseline.json" + assert build.main(["--baseline", str(path)]) == 0 + first = path.read_bytes() + assert build.main(["--baseline", str(path)]) == 0 + assert path.read_bytes() == first + assert build.main(["--diff", str(path)]) == 0 + report = json.loads(capsys.readouterr().out) + assert report["classification"] == "compatible" + saved = json.loads(path.read_text()) + saved["tools"].append({"definition": {"name": "removed", "inputSchema": {}}, "digest": "old"}) + path.write_text(json.dumps(saved)) + assert build.main(["--diff", str(path)]) == 1 + assert json.loads(capsys.readouterr().out)["classification"] == "breaking" + assert knowledge_mcp.CATALOGUE_PATH.read_bytes() == original + + +def test_checked_in_baseline_matches_current_contract(): + assert drift.baseline_json([e["definition"] for e in knowledge_mcp.catalogue()["tools"]]) == BASELINE.read_text() + + +@pytest.fixture +def registered_mcp(monkeypatch): + from flask import Flask, g + from routes import knowledge + + app = Flask(__name__) + app.config.update(SECRET_KEY="synthetic-contract-test", TESTING=True) + monkeypatch.setattr(knowledge, "api_authenticate_only", lambda **kwargs: lambda fn: fn) + knowledge.register_knowledge_routes(app, Mock(exempt=lambda fn: fn)) + user = {"username": "reader", "scopes": ["knowledge:read"]} + + @app.before_request + def identity(): + g.authenticated_user = user + + dispatch = Mock(return_value={"status": "ok"}) + monkeypatch.setattr(knowledge, "dispatch", dispatch) + monkeypatch.delenv("MCP_CONTRACT_DIGESTS_ENABLED", raising=False) + return app.test_client(), user, dispatch + + +def post_mcp(client, method, params=None, pin=None, path="/mcp"): + headers = {} if pin is None else {"X-MultiLLM-MCP-Contract": pin} + return client.post(path, json={"jsonrpc": "2.0", "id": 7, "method": method, "params": params or {}}, headers=headers) + + +@pytest.mark.parametrize("flag", [None, "", "false", "0", "malformed"]) +def test_registered_default_mcp_paths_ignore_pin_and_keep_bytes(registered_mcp, monkeypatch, flag): + from routes import knowledge + client, user, dispatch = registered_mcp + requests = [("tools/list", {}), ("tools/call", {"name": "knowledge_context", "arguments": {"query": "limits"}})] + expected = [post_mcp(client, method, params) for method, params in requests] + assert expected[0].json == {"jsonrpc": "2.0", "id": 7, "result": {"tools": [ + entry["definition"] for entry in knowledge._CATALOGUE["tools"] if entry["scope"] == "knowledge:read"]}} + if flag is not None: + monkeypatch.setenv("MCP_CONTRACT_DIGESTS_ENABLED", flag) + monkeypatch.setattr(drift, "contract_digest", Mock(side_effect=AssertionError("unexpected hash"))) + for (method, params), plain in zip(requests, expected): + for pin in [None, "", "bad", "0" * 64]: + actual = post_mcp(client, method, params, pin) + assert actual.status_code == plain.status_code == 200 + assert actual.data == plain.data + assert list(actual.headers) == list(plain.headers) + assert dispatch.call_count == 5 + dispatch.assert_called_with("context", user, {"query": "limits"}) + + +@pytest.mark.parametrize("scopes,admin,toolset", [ + (["knowledge:read"], False, None), (["knowledge:manage"], False, None), + ([], True, None), (["admin"], False, None), (["knowledge:read"], False, "core"), +]) +def test_registered_enabled_discovery_filters_before_hashing(registered_mcp, monkeypatch, scopes, admin, toolset): + from routes import knowledge + client, user, dispatch = registered_mcp + user.update(scopes=scopes, is_admin=admin) + monkeypatch.setenv("MCP_CONTRACT_DIGESTS_ENABLED", "true") + path = "/mcp" if toolset is None else f"/mcp?toolsets={toolset}" + response = post_mcp(client, "tools/list", path=path) + expected = [e["definition"] for e in knowledge._CATALOGUE["tools"] + if (admin or "admin" in scopes or e["scope"] in scopes) + and (toolset is None or e["toolset"] == toolset)] + assert response.status_code == 200 + result = response.json["result"] + assert result == drift.discovery_contract( + knowledge._CATALOGUE["tools"], ["admin"] if admin else scopes, + None if toolset is None else {toolset}, enabled=True) + assert result["_meta"]["contract_digest"] == drift.catalogue_digest(expected) + assert [t["name"] for t in result["tools"]] == [t["name"] for t in expected] + dispatch.assert_not_called() + + +@pytest.mark.parametrize("name,arguments", [ + ("knowledge_context", {"query": "limits"}), ("knowledge_exa_search", {"query": "limits"}), + ("knowledge_alexandria_inspect", {"id": "item-1"}), ("knowledge_policy_update", {}), + ("knowledge_skills_sync", {}), ("knowledge_handoff_get", {}), +]) +@pytest.mark.parametrize("pin", ["", "bad", "0" * 64]) +def test_registered_pin_mismatch_is_http_409_before_dispatch(registered_mcp, monkeypatch, name, arguments, pin): + client, user, dispatch = registered_mcp + user["is_admin"] = True + monkeypatch.setenv("MCP_CONTRACT_DIGESTS_ENABLED", "true") + response = post_mcp(client, "tools/call", {"name": name, "arguments": arguments}, pin) + assert response.status_code == 409 + assert response.json == {"jsonrpc": "2.0", "id": 7, "error": { + "code": "mcp_contract_mismatch", "message": "The pinned MCP tool contract has changed. Refresh discovery."}} + assert response.headers["Cache-Control"] == "no-store" + dispatch.assert_not_called() + + +def test_registered_matching_unpinned_and_changed_contract_calls(registered_mcp, monkeypatch): + from routes import knowledge + client, _, dispatch = registered_mcp + params = {"name": "knowledge_context", "arguments": {"query": "limits"}} + expected = post_mcp(client, "tools/call", params) + monkeypatch.setenv("MCP_CONTRACT_DIGESTS_ENABLED", "true") + tool = post_mcp(client, "tools/list").json["result"]["tools"][0] + old_pin = tool["_meta"]["contract_digest"] + assert post_mcp(client, "tools/call", params, old_pin).data == expected.data + assert post_mcp(client, "tools/call", params).data == expected.data + changed = copy.deepcopy(knowledge._TOOLS["knowledge_context"]["definition"]) + changed["inputSchema"]["x-revision"] = 2 + monkeypatch.setitem(knowledge._TOOLS["knowledge_context"], "definition", changed) + assert post_mcp(client, "tools/call", params, old_pin).status_code == 409 + assert post_mcp(client, "tools/call", params).data == expected.data + assert post_mcp(client, "tools/call", params, drift.contract_digest(changed)).data == expected.data + assert dispatch.call_count == 5 + + +def test_registered_authorization_precedes_pin_check(registered_mcp, monkeypatch): + client, _, dispatch = registered_mcp + monkeypatch.setenv("MCP_CONTRACT_DIGESTS_ENABLED", "true") + monkeypatch.setattr(drift, "contract_digest", Mock(side_effect=AssertionError("unauthorized hash"))) + denied = post_mcp(client, "tools/call", {"name": "knowledge_policy_update"}, "bad") + assert denied.status_code == 200 + assert "insufficient_scope" in denied.json["result"]["content"][0]["text"] + dispatch.assert_not_called() + + +@pytest.mark.parametrize("previous", [[], {}, {"format": "wrong", "tools": []}, {"format": drift.FORMAT, "tools": [None]}]) +def test_invalid_baseline_reports_error_without_writing(tmp_path, previous, capsys): + path = tmp_path / "invalid.json" + path.write_text(json.dumps(previous)) + original = path.read_bytes() + assert build.main(["--diff", str(path)]) == 2 + assert path.read_bytes() == original + assert "Contract baseline operation failed" in capsys.readouterr().err + + +def test_canonical_bounds_are_enforced(): + deep = None + for _ in range(66): + deep = [deep] + for value in [deep, [None] * 65537, "x" * drift.MAX_CANONICAL_BYTES, 10**1000]: + with pytest.raises(ValueError): + drift.canonical_value(value) + + +def test_output_widening_requires_review_and_boolean_input_narrowing_breaks(): + old = {**TOOL, "outputSchema": {"type": "string"}} + new = {**TOOL, "outputSchema": {"type": ["string", "null"]}} + assert drift.diff_contracts([old], [new])["classification"] == "review-required" + assert drift.diff_contracts([{**TOOL, "inputSchema": True}], [{**TOOL, "inputSchema": False}])["classification"] == "breaking" + + +def test_baseline_modes_cannot_overwrite_worker_catalogue(capsys): + for option in ("--baseline", "--diff"): + assert build.main([option, str(knowledge_mcp.CATALOGUE_PATH)]) == 2 + assert "cannot overwrite" in capsys.readouterr().err diff --git a/tests/test_mcp_contract_drift_worker.mjs b/tests/test_mcp_contract_drift_worker.mjs new file mode 100644 index 00000000..372dd5a2 --- /dev/null +++ b/tests/test_mcp_contract_drift_worker.mjs @@ -0,0 +1,179 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import test from "node:test"; +import { canonicalContract, canonicalValue, contractDigest, catalogueDigest, discoveryContract, digestsEnabled, checkContractPin } from "../worker/knowledge/contract-drift.mjs"; +import { dispatchNative } from "../worker/knowledge/native.mjs"; +import { loadWorkerModule } from "./helpers/load_cloudflare_worker.mjs"; +import { generateIntegrationCredential } from "../scripts/intelligence_operator.mjs"; +import { fixture, principal } from "./knowledge_fixture.mjs"; + +const baseline = JSON.parse(await readFile(new URL("../docs/mcp-contract-baseline.json", import.meta.url), "utf8")); +const catalogue = JSON.parse(await readFile(new URL("../worker/knowledge-mcp-catalogue.json", import.meta.url), "utf8")); + +test("shared Python/Worker canonical vectors and current catalogue digests", async () => { + for (const v of baseline.vectors) { + assert.equal(canonicalContract(v.definition, v.contract_version), v.canonical); + assert.equal(await contractDigest(v.definition, v.contract_version), v.digest); + } + for (const entry of baseline.tools) assert.equal(await contractDigest(entry.definition), entry.digest); + assert.equal(canonicalValue(0), canonicalValue(-0)); +}); + +test("unknown fields retained, arrays ordered, and unsafe values rejected", async () => { + const tool = { name: "test", inputSchema: { b: 1, a: { type: "string" } } }; + assert.equal(await contractDigest(tool), await contractDigest({ inputSchema: { a: { type: "string" }, b: 1 }, name: "test" })); + assert.notEqual(await contractDigest(tool), await contractDigest({ ...tool, inputSchema: { ...tool.inputSchema, "x-vendor": [1, 2] } })); + assert.notEqual(canonicalValue([1, 2]), canonicalValue([2, 1])); + for (const value of [NaN, Infinity, 2 ** 53, "\ud800", undefined]) assert.throws(() => canonicalValue(value)); +}); + +test("flag is default off and malformed warnings contain no values", () => { + const warnings = []; + for (const value of [undefined, "", false, "false", "0"]) assert.equal(digestsEnabled(value, m => warnings.push(m)), false); + assert.equal(warnings.length, 0); + assert.equal(digestsEnabled("bad", m => warnings.push(m)), false); + assert.equal(digestsEnabled("bad", m => warnings.push(m)), false); + assert.equal(warnings.length, 1); + assert.ok(!warnings[0].includes("bad")); + for (const value of [true, "true", "1", " TRUE "]) assert.equal(digestsEnabled(value), true); +}); + +test("discovery digests describe only authorized tools and preserve off output", async () => { + const result = await discoveryContract(catalogue.tools, ["knowledge:read"], { toolsets: ["core"], enabled: true }); + assert.deepEqual(result.tools.map(t => t.name), ["knowledge_context", "knowledge_search", "knowledge_artifact"]); + assert.equal(result._meta.contract_digest, await catalogueDigest(result.tools)); + assert.ok(result.tools.every(t => t._meta.contract_digest)); + const plain = await discoveryContract(catalogue.tools, ["knowledge:read"], { toolsets: ["core"] }); + assert.deepEqual(plain, { tools: catalogue.tools.filter(e => e.toolset === "core").map(e => e.definition) }); + assert.notEqual(result._meta.contract_digest, (await discoveryContract(catalogue.tools, ["knowledge:manage"], { enabled: true }))._meta.contract_digest); + assert.deepEqual(catalogue.tools.map(e => e.definition), baseline.tools.map(e => e.definition)); +}); + +test("native pin mismatch denies before storage, billing or fetch; disabled ignores header", async () => { + let calls = 0; + const authority = { call: async () => { calls++; throw new Error("dispatch reached"); } }; + await assert.rejects(dispatchNative({ MCP_CONTRACT_DIGESTS_ENABLED: "true" }, authority, principal, "native.exa_search", { query: "x" }, { contractPin: "0".repeat(64) }), { code: "mcp_contract_mismatch", status: 409 }); + assert.equal(calls, 0); + await assert.rejects(dispatchNative({}, authority, principal, "native.exa_search", { query: "x" }, { contractPin: "bad" }), /dispatch reached/); + assert.equal(calls, 1); + const f = await fixture(); + let fetched = 0; + const fetchImpl = async () => { fetched++; return Response.json({ results: [] }); }; + const definition = catalogue.tools.find(e => e.definition.name === "knowledge_exa_search").definition; + const pin = await contractDigest(definition); + const plain = await dispatchNative(f.env, f.authority, principal, "native.exa_search", { query: "x" }, { fetchImpl, contractPin: "bad" }); + f.env.MCP_CONTRACT_DIGESTS_ENABLED = "true"; + const matched = await dispatchNative(f.env, f.authority, principal, "native.exa_search", { query: "x" }, { fetchImpl, contractPin: pin }); + const unpinned = await dispatchNative(f.env, f.authority, principal, "native.exa_search", { query: "x" }, { fetchImpl }); + assert.deepEqual(plain, matched); + assert.deepEqual(plain, unpinned); + assert.equal(fetched, 3); +}); + +test("pin helper bypasses disabled and unpinned calls without hashing", async () => { + await checkContractPin(null, "bad", { enabled: false }); + await checkContractPin(null, undefined, { enabled: true }); + await assert.rejects(checkContractPin(baseline.vectors[0].definition, "bad", { enabled: true }), { code: "mcp_contract_mismatch", status: 409 }); +}); + + +test("canonical operational bounds reject oversized and deep schemas", () => { + let deep = null; + for (let i = 0; i < 66; i++) deep = [deep]; + for (const value of [deep, Array(65537).fill(null), "x".repeat(256 * 1024)]) assert.throws(() => canonicalValue(value)); +}); + + +const edgeWorker = (await loadWorkerModule()).default; +const edgeReader = await generateIntegrationCredential(); +function edgeEnvironment(flag) { + const dispatched = []; + const env = { + ADMIN_API_KEY: "synthetic-contract-admin", AUTH_STORAGE_BACKEND: "d1", + INTELLIGENCE_DB: { prepare() { return { bind() { return { async first() { + return { id: "integration:contract", scopes: JSON.stringify(["knowledge:read"]), version: 1, + created_at: "2026-10-09T00:00:00Z", revoked_at: null, key_prefix: edgeReader.keyPrefix, key_hash: edgeReader.keyHash }; + } }; } }; } }, + KNOWLEDGE_SERVICE: { async fetch(_url, init) { + dispatched.push(JSON.parse(init.body)); + return Response.json({ version: 1, result: { status: "ok" } }); + } }, + MULTILLM_PROXY_CONTAINER: { getByName() { throw new Error("unexpected Container dispatch"); } }, + }; + if (flag !== undefined) env.MCP_CONTRACT_DIGESTS_ENABLED = flag; + return { env, dispatched }; +} +function edgeRequest(method, params = {}, pin, { key = "synthetic-contract-admin", toolsets } = {}) { + return new Request(`https://gateway.example/mcp${toolsets ? `?toolsets=${toolsets}` : ""}`, { + method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json", + ...(pin === undefined ? {} : { "X-MultiLLM-MCP-Contract": pin }) }, + body: JSON.stringify({ jsonrpc: "2.0", id: 7, method, params }), + }); +} +const responseBytes = async response => ({ status: response.status, headers: [...response.headers], body: await response.text() }); + +test("registered edge MCP disabled flags preserve response bytes, headers and dispatch payloads", async () => { + const requests = [["tools/list", {}], ["tools/call", { name: "knowledge_context", arguments: { query: "limits" } }]]; + for (const flag of [undefined, "", "false", "0", "malformed"]) { + const { env, dispatched } = edgeEnvironment(); + const expected = []; + for (const [method, params] of requests) expected.push(await responseBytes(await edgeWorker.fetch(edgeRequest(method, params), env))); + assert.deepEqual(JSON.parse(expected[0].body), { jsonrpc: "2.0", id: 7, result: { tools: catalogue.tools.map(e => e.definition) } }); + if (flag !== undefined) env.MCP_CONTRACT_DIGESTS_ENABLED = flag; + for (const [index, [method, params]] of requests.entries()) { + for (const pin of [undefined, "", "bad", "0".repeat(64)]) { + assert.deepEqual(await responseBytes(await edgeWorker.fetch(edgeRequest(method, params, pin), env)), expected[index]); + } + } + assert.equal(dispatched.length, 5); + for (const payload of dispatched) assert.deepEqual(payload, dispatched[0]); + } +}); + +test("registered edge enabled discovery hashes only authorized contracts and selected toolsets", async () => { + const { env, dispatched } = edgeEnvironment("true"); + for (const options of [{}, { key: edgeReader.key }, { key: edgeReader.key, toolsets: "core" }]) { + const response = await edgeWorker.fetch(edgeRequest("tools/list", {}, undefined, options), env); + assert.equal(response.status, 200); + const result = (await response.json()).result; + const scopes = options.key ? ["knowledge:read"] : ["knowledge:read", "knowledge:manage"]; + assert.deepEqual(result, await discoveryContract(catalogue.tools, scopes, + { enabled: true, toolsets: options.toolsets ? [options.toolsets] : null })); + assert.equal(result._meta.contract_digest, await catalogueDigest(result.tools)); + } + assert.equal(dispatched.length, 0); +}); + +test("registered edge mismatches return real HTTP 409 before dispatch for every tool kind", async () => { + const { env, dispatched } = edgeEnvironment("true"); + for (const name of ["knowledge_context", "knowledge_exa_search", "knowledge_alexandria_inspect", + "knowledge_policy_update", "knowledge_skills_sync", "knowledge_handoff_get"]) { + for (const pin of ["", "bad", "0".repeat(64)]) { + const response = await edgeWorker.fetch(edgeRequest("tools/call", { name, arguments: {} }, pin), env); + assert.equal(response.status, 409); + assert.deepEqual(await response.json(), { jsonrpc: "2.0", id: 7, error: { + code: "mcp_contract_mismatch", message: "The pinned MCP tool contract has changed. Refresh discovery." } }); + assert.equal(response.headers.get("cache-control"), "no-store"); + } + } + assert.equal(dispatched.length, 0); +}); + +test("registered edge matching and unpinned calls preserve results; authorization precedes pins", async () => { + const { env, dispatched } = edgeEnvironment(); + const params = { name: "knowledge_context", arguments: { query: "limits" } }; + const expected = await responseBytes(await edgeWorker.fetch(edgeRequest("tools/call", params), env)); + env.MCP_CONTRACT_DIGESTS_ENABLED = "true"; + const result = (await (await edgeWorker.fetch(edgeRequest("tools/list"), env)).json()).result; + const tool = result.tools.find(t => t.name === params.name); + for (const pin of [undefined, tool._meta.contract_digest]) { + assert.deepEqual(await responseBytes(await edgeWorker.fetch(edgeRequest("tools/call", params, pin), env)), expected); + } + const stale = await contractDigest({ ...tool, inputSchema: { ...tool.inputSchema, "x-revision": "older" } }); + assert.equal((await edgeWorker.fetch(edgeRequest("tools/call", params, stale), env)).status, 409); + assert.deepEqual(await responseBytes(await edgeWorker.fetch(edgeRequest("tools/call", params), env)), expected); + const denied = await edgeWorker.fetch(edgeRequest("tools/call", { name: "knowledge_policy_update" }, "bad", { key: edgeReader.key }), env); + assert.equal(denied.status, 200); + assert.match((await denied.json()).result.content[0].text, /insufficient_scope/); + assert.equal(dispatched.length, 4); +}); diff --git a/worker/container-env.mjs b/worker/container-env.mjs index f678771b..6e54e446 100644 --- a/worker/container-env.mjs +++ b/worker/container-env.mjs @@ -22,6 +22,7 @@ const DIRECT_ENV_KEYS = [ "NATIVE_TOKEN_COUNT_ENDPOINTS_JSON", "INTELLIGENCE_NANOGPT_SUBSCRIPTION_API_KEY", "WORKBENCH_WORKER_URL", + "MCP_CONTRACT_DIGESTS_ENABLED", "CONNECTION_PROFILES_DB_PATH", "RATE_LIMIT_ENABLED", "RATE_LIMIT_RPM", diff --git a/worker/knowledge-edge.mjs b/worker/knowledge-edge.mjs index 5d3baa22..0912bcd2 100644 --- a/worker/knowledge-edge.mjs +++ b/worker/knowledge-edge.mjs @@ -12,6 +12,7 @@ import { authStorageBackend } from "./container-env.mjs"; import { activeUsersByPrefix, adminUsernames, grantsAdmin, keyControlsPermit, validUser } from "./control-users-d1.mjs"; import { INTEGRATION_SCOPES, lookupIntegrationPrincipal } from "./intelligence-auth-d1.mjs"; import { logFailure } from "./log.mjs"; +import { contractPinMismatch, digestsEnabled, discoveryContract } from "./knowledge/contract-drift.mjs"; import { SYNC_REQUEST_BYTES } from "./knowledge/skills-validation.mjs"; import { protectPayload, secretScanMode, SECRET_SCAN_HEADER } from "./secret-firewall.mjs"; @@ -345,6 +346,8 @@ async function callTool(env, request, principal, id, params) { if (!permits(principal, entry.scope)) { return failure("insufficient_scope", "The key is not authorized for this Knowledge tool."); } + const mismatch = await contractPinMismatch(entry.definition, request.headers.get("X-MultiLLM-MCP-Contract"), env.MCP_CONTRACT_DIGESTS_ENABLED); + if (mismatch) return rpcError(id, mismatch.code, mismatch.message, mismatch.status); const args = params.arguments ?? {}; if (!isRecord(args)) return rpcError(id, -32602, "Tool arguments must be an object."); try { @@ -408,8 +411,9 @@ async function handleMcp(request, env, principal) { if (toolsets && (!toolsets.size || [...toolsets].some(name => !catalogue.toolsets.includes(name)))) { return rpcError(id, -32602, `Unknown toolset. Use any of: ${catalogue.toolsets.join(", ")}.`); } - return rpcResult(id, { tools: catalogue.tools.filter(entry => permits(principal, entry.scope) - && (!toolsets || toolsets.has(entry.toolset))).map(entry => entry.definition) }); + return rpcResult(id, await discoveryContract(catalogue.tools, principal.scopes, { + toolsets: toolsets === null ? null : [...toolsets], enabled: digestsEnabled(env.MCP_CONTRACT_DIGESTS_ENABLED), + })); } if (method !== "tools/call") return rpcError(id, -32601, "Method not found."); return callTool(env, request, principal, id, params); diff --git a/worker/knowledge/contract-drift.mjs b/worker/knowledge/contract-drift.mjs new file mode 100644 index 00000000..f485e88b --- /dev/null +++ b/worker/knowledge/contract-drift.mjs @@ -0,0 +1,99 @@ +/** Offline-compatible MCP contracts; no provider, storage or permission side effects. */ +import { fail, isRecord, KnowledgeError } from "./contracts.mjs"; + +export const CONTRACT_VERSION = "1.0.0"; +const MAX_CANONICAL_BYTES = 256 * 1024; +const MAX_DEPTH = 64; +const MAX_NODES = 65536; +let warned = false; + +export function digestsEnabled(value, warn = message => console.warn(message)) { + if (typeof value === "boolean") return value; + if (value === undefined || value === null) return false; + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + if (["", "false", "0"].includes(normalized)) return false; + if (["true", "1"].includes(normalized)) return true; + } + if (!warned) { + warn("Invalid MCP_CONTRACT_DIGESTS_ENABLED; contract digests are disabled."); + warned = true; + } + return false; +} + +const scalarOrder = (a, b) => { + const left = Array.from(a, char => char.codePointAt(0)); + const right = Array.from(b, char => char.codePointAt(0)); + for (let i = 0; i < Math.min(left.length, right.length); i++) if (left[i] !== right[i]) return left[i] - right[i]; + return left.length - right.length; +}; +const text = value => { + if (!value.isWellFormed()) throw new Error("Contract strings must contain Unicode scalar values."); + return value; +}; + +export function canonicalValue(value) { + let remaining = MAX_NODES; + const node = (item, depth) => { + if (depth > MAX_DEPTH || --remaining < 0) throw new Error("Contract exceeds canonical depth or node limits."); + if (item === null) return ["null"]; + if (typeof item === "boolean") return ["boolean", item]; + if (typeof item === "number") { + if (!Number.isFinite(item) || Math.abs(item) > Number.MAX_SAFE_INTEGER) throw new Error("Contract numbers must be finite and within the interoperable range."); + const bytes = new ArrayBuffer(8); + new DataView(bytes).setFloat64(0, item === 0 ? 0 : item, false); + return ["number", Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, "0")).join("")]; + } + if (typeof item === "string") return ["string", text(item)]; + if (Array.isArray(item)) return ["array", item.map(child => node(child, depth + 1))]; + if (isRecord(item) && Object.getPrototypeOf(item) === Object.prototype) { + return ["object", Object.keys(item).sort(scalarOrder).map(key => [text(key), node(item[key], depth + 1)])]; + } + throw new Error("Contract contains a non-JSON value."); + }; + const encoded = JSON.stringify(node(value, 0)); + if (new TextEncoder().encode(encoded).length > MAX_CANONICAL_BYTES) throw new Error("Contract exceeds canonical byte limit."); + return encoded; +} + +function contractPayload(definition, contractVersion) { + if (!isRecord(definition) || typeof definition.name !== "string" || !Object.hasOwn(definition, "inputSchema")) throw new Error("A tool contract requires a name and inputSchema."); + return { name: definition.name, inputSchema: definition.inputSchema, outputSchema: definition.outputSchema ?? null, contractVersion }; +} + +export const canonicalContract = (definition, contractVersion = CONTRACT_VERSION) => canonicalValue(contractPayload(definition, contractVersion)); +const sha256 = async value => { + const hash = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)); + return Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2, "0")).join(""); +}; +export const contractDigest = (definition, contractVersion = CONTRACT_VERSION) => sha256(canonicalContract(definition, contractVersion)); +export const catalogueDigest = (definitions, contractVersion = CONTRACT_VERSION) => sha256(canonicalValue( + [...definitions].sort((a, b) => scalarOrder(a.name, b.name)).map(tool => contractPayload(tool, contractVersion)))); + +export async function discoveryContract(entries, scopes, { toolsets = null, enabled = false } = {}) { + const tools = entries.filter(entry => (scopes.includes("admin") || scopes.includes(entry.scope)) + && (toolsets === null || toolsets.includes(entry.toolset))).map(entry => entry.definition); + if (!enabled) return { tools }; + return { tools: await Promise.all(tools.map(async tool => ({ ...tool, _meta: { ...tool._meta, contract_digest: await contractDigest(tool) } }))), + _meta: { contract_digest: await catalogueDigest(tools) } }; +} + +export async function checkContractPin(definition, pin, { enabled = false } = {}) { + if (!enabled || pin === undefined || pin === null) return; + if (typeof pin !== "string" || pin.length !== 64 || pin !== await contractDigest(definition)) { + fail("mcp_contract_mismatch", "The pinned MCP tool contract has changed. Refresh discovery.", 409); + } +} + + +/** Translate only a local pin rejection for the public MCP HTTP boundary. */ +export async function contractPinMismatch(definition, pin, flag) { + try { + await checkContractPin(definition, pin, { enabled: digestsEnabled(flag) }); + return null; + } catch (error) { + if (!(error instanceof KnowledgeError) || error.code !== "mcp_contract_mismatch") throw error; + return { code: error.code, message: error.message, status: error.status }; + } +} diff --git a/worker/knowledge/native.mjs b/worker/knowledge/native.mjs index a6248775..d49cb380 100644 --- a/worker/knowledge/native.mjs +++ b/worker/knowledge/native.mjs @@ -9,6 +9,7 @@ import { metered } from "./operations.mjs"; import { callTool } from "./providers/mcp.mjs"; import { jsonPost, ProviderError, requestJSON } from "./providers/transport.mjs"; import { providerStatus } from "./providers/index.mjs"; +import { checkContractPin, digestsEnabled } from "./contract-drift.mjs"; export const NATIVE_TOOLS = TOOLS; export const NATIVE_OPERATIONS = Object.keys(TOOLS).map(name => `native.${name}`); @@ -199,6 +200,8 @@ export async function dispatchNative(env, authority, principal, operation, paylo if (!isRecord(payload) || JSON.stringify(payload).length > MAX_ARGUMENT_BYTES) invalid(tool, ""); check(tool, spec.input, payload, ""); authorizeArguments(tool, payload, principal); + await checkContractPin({ name: `knowledge_${tool}`, inputSchema: spec.input }, options.contractPin, + { enabled: digestsEnabled(env.MCP_CONTRACT_DIGESTS_ENABLED) }); const snapshot = await authority.call("catalogue.state"); const allocation = snapshot.policy.providers[spec.provider]; if (!snapshot.policy.enabled || !allocation?.enabled) {