@fragments-sdk/mcp 0.10.1 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -84
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +7 -153
- package/dist/bin.js.map +1 -1
- package/dist/index.d.ts +1443 -0
- package/dist/index.js +1107 -207
- package/dist/index.js.map +1 -1
- package/package.json +9 -33
- package/dist/chunk-7D4SUZUM.js +0 -38
- package/dist/chunk-7D4SUZUM.js.map +0 -1
- package/dist/chunk-KGFM5SCE.js +0 -4263
- package/dist/chunk-KGFM5SCE.js.map +0 -1
- package/dist/chunk-VRPDT3Y6.js +0 -52
- package/dist/chunk-VRPDT3Y6.js.map +0 -1
- package/dist/chunk-WDQPNHZ2.js +0 -143
- package/dist/chunk-WDQPNHZ2.js.map +0 -1
- package/dist/dist-LVC53MY5.js +0 -61000
- package/dist/dist-LVC53MY5.js.map +0 -1
- package/dist/init.js +0 -175
- package/dist/init.js.map +0 -1
- package/dist/rules-JUZ3RABB.js +0 -8
- package/dist/rules-JUZ3RABB.js.map +0 -1
- package/dist/sass.node-4XJK6YBF-CPK77BO6.js +0 -130797
- package/dist/sass.node-4XJK6YBF-CPK77BO6.js.map +0 -1
- package/dist/server.js +0 -12
- package/dist/server.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/custom-json.ts","../src/orama-index.ts","../src/scoring.ts","../src/search-config.ts","../src/index.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { mcpSnapshotSchema, type McpSnapshot } from '@fragments-sdk/core';\nimport type {\n CompiledBlock,\n CompiledFragment,\n CompiledTokenData,\n} from '@fragments-sdk/context/types';\nimport type { SerializedComponentGraph } from '@fragments-sdk/context/graph';\nimport type { DesignSystemData } from '../types.js';\nimport type { DataAdapter } from './types.js';\nimport {\n blockFromCompiledBlock,\n buildCapabilities,\n componentFromCompiledFragment,\n tokensFromCompiledTokenData,\n validateSnapshot,\n} from './snapshot-converters.js';\n\nexport class CustomJsonAdapter implements DataAdapter {\n readonly name = 'custom-json';\n\n constructor(private filePath: string) {}\n\n discover(): string[] {\n return existsSync(this.filePath) ? [this.filePath] : [];\n }\n\n async load(_projectRoot = ''): Promise<DesignSystemData> {\n if (!existsSync(this.filePath)) {\n throw new Error(`Custom data file not found: ${this.filePath}`);\n }\n\n const content = await readFile(this.filePath, 'utf-8');\n const raw = JSON.parse(content) as Record<string, unknown>;\n\n if (\n raw.schemaVersion === 1 &&\n typeof raw.sourceType === 'string' &&\n raw.components &&\n typeof raw.components === 'object'\n ) {\n const snapshot = mcpSnapshotSchema.parse(raw) as McpSnapshot;\n return {\n snapshot,\n components: snapshot.components,\n blocks: snapshot.blocks,\n tokens: snapshot.tokens,\n graph: snapshot.graph as SerializedComponentGraph | undefined,\n performanceSummary: snapshot.performanceSummary,\n packageMap: snapshot.packageMap,\n defaultPackageName: snapshot.defaultPackageName,\n capabilities: new Set(snapshot.capabilities),\n };\n }\n\n if (!raw.components || typeof raw.components !== 'object') {\n throw new Error(\n `Invalid design system data: \"components\" field is required and must be an object. ` +\n `File: ${this.filePath}`,\n );\n }\n\n const packageMap =\n (raw.packageMap as Record<string, string> | undefined) ?? {};\n const defaultPackageName = raw.defaultPackageName as string | undefined;\n const metadata = raw.metadata as\n | {\n designSystemName?: string;\n packageName?: string;\n importPath?: string;\n revision?: string;\n updatedAt?: string;\n }\n | undefined;\n const components = Object.fromEntries(\n Object.entries(raw.components as Record<string, CompiledFragment>).map(\n ([key, fragment]) => [\n key,\n componentFromCompiledFragment({\n id: key,\n fragment,\n sourceType: 'custom-json',\n packageName: packageMap[fragment.meta.name] ?? defaultPackageName,\n importPath: packageMap[fragment.meta.name] ?? defaultPackageName,\n }),\n ],\n ),\n );\n const blocks = raw.blocks\n ? Object.fromEntries(\n Object.entries(raw.blocks as Record<string, CompiledBlock>).map(\n ([key, block]) => [key, blockFromCompiledBlock(key, block)],\n ),\n )\n : undefined;\n const tokens = raw.tokens\n ? tokensFromCompiledTokenData(raw.tokens as CompiledTokenData)\n : undefined;\n const snapshot = validateSnapshot({\n schemaVersion: 1,\n sourceType: 'custom-json',\n sourceLabel: this.filePath,\n capabilities: buildCapabilities({\n components,\n blocks,\n tokens,\n graph: raw.graph,\n performanceSummary: raw.performanceSummary,\n }),\n metadata: {\n designSystemName: metadata?.designSystemName,\n packageName: metadata?.packageName ?? defaultPackageName,\n importPath: metadata?.importPath ?? defaultPackageName,\n revision: metadata?.revision,\n updatedAt: metadata?.updatedAt,\n },\n components,\n blocks,\n tokens,\n graph: raw.graph as SerializedComponentGraph | undefined,\n performanceSummary:\n raw.performanceSummary as McpSnapshot['performanceSummary'],\n packageMap,\n defaultPackageName,\n });\n\n return {\n snapshot,\n components: snapshot.components,\n blocks: snapshot.blocks,\n tokens: snapshot.tokens,\n graph: snapshot.graph as SerializedComponentGraph | undefined,\n performanceSummary: snapshot.performanceSummary,\n packageMap: snapshot.packageMap,\n defaultPackageName: snapshot.defaultPackageName,\n capabilities: new Set(snapshot.capabilities),\n };\n }\n}\n","/**\n * Orama-powered BM25 search indexes for components, blocks, and tokens.\n *\n * Replaces the bag-of-words keyword scorer with Orama's built-in BM25 engine,\n * which provides IDF weighting (automatically downweights common terms like\n * \"page\", \"section\", \"content\"), stemming, and field-level boosting.\n */\n\nimport { create, insertMultiple, search } from '@orama/orama';\nimport type { AnyOrama } from '@orama/orama';\nimport type { McpBlock, McpComponent, McpTokenData } from '@fragments-sdk/core';\nimport type {\n CompiledBlock,\n CompiledFragment,\n CompiledTokenData,\n} from '@fragments-sdk/context/types';\nimport type { ScoredResult, EntryKind } from './search.js';\n\n// ---------------------------------------------------------------------------\n// Synonym map (shared with search.ts — imported via re-export)\n// ---------------------------------------------------------------------------\n\nexport const SYNONYM_MAP: Record<string, string[]> = {\n 'form': ['input', 'field', 'submit', 'validation'],\n 'input': ['form', 'field', 'text', 'entry'],\n 'button': ['action', 'click', 'submit', 'trigger'],\n 'action': ['button', 'click', 'trigger'],\n 'submit': ['button', 'form', 'action', 'send'],\n 'alert': ['notification', 'message', 'warning', 'error', 'feedback'],\n 'notification': ['alert', 'message', 'toast'],\n 'feedback': ['form', 'comment', 'review', 'rating'],\n 'card': ['container', 'panel', 'box', 'content'],\n 'toggle': ['switch', 'checkbox', 'boolean', 'on/off'],\n 'switch': ['toggle', 'checkbox', 'boolean'],\n 'badge': ['tag', 'label', 'status', 'indicator'],\n 'status': ['badge', 'indicator', 'state'],\n 'login': ['auth', 'signin', 'authentication', 'form'],\n 'auth': ['login', 'signin', 'authentication'],\n 'chat': ['message', 'conversation', 'ai'],\n 'table': ['data', 'grid', 'list', 'rows'],\n 'textarea': ['text', 'input', 'multiline', 'area', 'comment'],\n 'area': ['textarea', 'multiline', 'text'],\n 'landing': ['page', 'hero', 'marketing', 'section', 'layout'],\n 'hero': ['landing', 'marketing', 'banner', 'headline', 'section'],\n 'marketing': ['landing', 'hero', 'pricing', 'testimonial', 'cta'],\n 'cta': ['marketing', 'banner', 'action', 'button'],\n 'testimonial': ['marketing', 'review', 'quote', 'feedback'],\n 'layout': ['stack', 'grid', 'box', 'container', 'page'],\n 'page': ['layout', 'landing', 'section', 'container'],\n 'section': ['hero', 'feature', 'testimonial', 'cta', 'faq'],\n 'pricing': ['card', 'plan', 'tier', 'marketing'],\n 'plan': ['pricing', 'card', 'tier', 'subscription'],\n 'dashboard': ['metrics', 'stats', 'chart', 'card', 'grid'],\n 'metrics': ['dashboard', 'stats', 'progress', 'number'],\n 'stats': ['metrics', 'dashboard', 'progress', 'badge'],\n 'chart': ['dashboard', 'metrics', 'data', 'graph'],\n};\n\n// ---------------------------------------------------------------------------\n// Query expansion via synonyms\n// ---------------------------------------------------------------------------\n\n/**\n * Expand a query string with synonym terms.\n * Returns the expanded query as a single string suitable for Orama `term`.\n */\nexport function expandQuery(query: string): string {\n const terms = query.toLowerCase().split(/\\s+/).filter(Boolean);\n const expanded = new Set(terms);\n for (const term of terms) {\n const synonyms = SYNONYM_MAP[term];\n if (synonyms) {\n for (const syn of synonyms) expanded.add(syn);\n }\n }\n return Array.from(expanded).join(' ');\n}\n\n// ---------------------------------------------------------------------------\n// Shared two-pass search pattern\n// ---------------------------------------------------------------------------\n\ninterface TwoPassConfig {\n index: AnyOrama;\n query: string;\n properties: string[];\n boost: Record<string, number>;\n limit: number;\n kind: EntryKind;\n}\n\n/**\n * Two-pass BM25 search: original terms weighted 2x, synonym-expanded terms 1x.\n * Prevents synonym noise from outranking truly relevant results.\n */\nexport function twoPassSearch(config: TwoPassConfig): ScoredResult[] {\n const { index, query, properties, boost, limit, kind } = config;\n\n const baseConfig = {\n mode: 'fulltext' as const,\n properties,\n boost,\n limit,\n };\n\n const originalTermsQuery = query.toLowerCase().split(/\\s+/).filter(Boolean).join(' ');\n const expandedQuery = expandQuery(query);\n\n // First pass: original terms only (moderate threshold to filter weak matches)\n const originalResults = search(index, { term: originalTermsQuery, ...baseConfig, threshold: 0.8 });\n // Second pass: synonym-expanded (permissive — scoring handles relevance via 1x weight)\n const expandedResults = search(index, { term: expandedQuery, ...baseConfig, threshold: 1 });\n\n type Hit = { score: number; document: { name: string } };\n const origHits = (originalResults as unknown as { hits: Hit[] }).hits;\n const expHits = (expandedResults as unknown as { hits: Hit[] }).hits;\n\n // Combine scores: original terms get 2x weight\n const scoreMap = new Map<string, number>();\n for (const hit of origHits) {\n scoreMap.set(hit.document.name, (hit.score || 0) * 2);\n }\n for (const hit of expHits) {\n const name = hit.document.name;\n const existing = scoreMap.get(name) ?? 0;\n scoreMap.set(name, existing + (hit.score || 0));\n }\n\n const scored: ScoredResult[] = [];\n for (const [name, score] of scoreMap) {\n if (score > 0) {\n scored.push({ name, kind, rank: scored.length, score });\n }\n }\n\n scored.sort((a, b) => b.score - a.score);\n scored.forEach((s, i) => { s.rank = i; });\n\n return scored;\n}\n\n// ---------------------------------------------------------------------------\n// Component index\n// ---------------------------------------------------------------------------\n\nconst componentSchema = {\n name: 'string' as const,\n description: 'string' as const,\n category: 'string' as const,\n tags: 'string' as const,\n whenUsed: 'string' as const,\n patterns: 'string' as const,\n variants: 'string' as const,\n status: 'string' as const,\n};\n\nexport type ComponentIndex = AnyOrama;\n\nfunction isCompiledFragment(\n value: McpComponent | CompiledFragment,\n): value is CompiledFragment {\n return 'meta' in value;\n}\n\nfunction normalizeComponent(\n value: McpComponent | CompiledFragment,\n): McpComponent {\n if (!isCompiledFragment(value)) return value;\n return {\n id: value.filePath ?? value.meta.name,\n name: value.meta.name,\n description: value.meta.description ?? '',\n category: value.meta.category ?? 'uncategorized',\n status: value.meta.status ?? 'stable',\n tags: value.meta.tags ?? [],\n props: {},\n propsSummary:\n value.propsSummary ??\n value.contract?.propsSummary ??\n Object.entries(value.props ?? {}).map(\n ([propName, prop]) =>\n `${propName}${prop.required ? ' (required)' : ''}: ${prop.type}`,\n ),\n examples: (value.variants ?? []).map((variant) => ({\n name: variant.name,\n description: variant.description,\n code: variant.code,\n })),\n relations: (value.relations ?? []).map((relation) => ({\n componentName: relation.component,\n relationship: relation.relationship,\n note: relation.note,\n })),\n compoundChildren: [],\n guidance: {\n when: value.usage?.when ?? [],\n whenNot: value.usage?.whenNot ?? [],\n guidelines: value.usage?.guidelines ?? [],\n accessibility: value.usage?.accessibility ?? [],\n dos: value.usage?.when ?? [],\n donts: value.usage?.whenNot ?? [],\n patterns: [],\n },\n sourceType: 'fragments-json',\n sourcePath: value.sourcePath ?? value.filePath,\n metadata: {\n a11yRules: value.contract?.a11yRules ?? [],\n scenarioTags: value.contract?.scenarioTags ?? [],\n },\n };\n}\n\nexport function buildComponentIndex(\n fragments: Array<McpComponent | CompiledFragment>,\n): ComponentIndex {\n const db = create({ schema: componentSchema, language: 'english' });\n const normalized = fragments.map(normalizeComponent);\n\n const docs = normalized.map((f) => ({\n name: f.name,\n description: f.description ?? '',\n category: f.category ?? '',\n tags: (f.tags ?? []).join(' '),\n whenUsed: (f.guidance.when ?? []).join(' '),\n patterns: (f.guidance.patterns ?? [])\n .map(\n (pattern: McpComponent['guidance']['patterns'][number]) =>\n `${pattern.name} ${pattern.description || ''}`,\n )\n .join(' '),\n variants: f.examples\n .map(\n (example: McpComponent['examples'][number]) =>\n `${example.name} ${example.description || ''}`,\n )\n .join(' '),\n status: f.status ?? 'stable',\n }));\n\n insertMultiple(db, docs);\n return db;\n}\n\nexport function searchComponents(\n query: string,\n index: ComponentIndex,\n fragments: Array<McpComponent | CompiledFragment>,\n limit = 50,\n): ScoredResult[] {\n const normalized = fragments.map(normalizeComponent);\n const boostConfig = {\n mode: 'fulltext' as const,\n properties: ['name', 'whenUsed', 'description', 'patterns', 'category', 'tags', 'variants'],\n boost: {\n name: 3,\n whenUsed: 2.5,\n description: 2,\n patterns: 1.5,\n category: 1.5,\n tags: 1.5,\n variants: 1,\n },\n limit,\n };\n\n // Two-pass search: original terms weighted 2x, synonym terms 1x\n // This prevents synonym noise (\"box\", \"container\") from outranking truly relevant results\n const originalTermsList = query.toLowerCase().split(/\\s+/).filter(Boolean);\n const originalTermsQuery = originalTermsList.join(' ');\n const expandedQuery = expandQuery(query);\n\n // First pass: original terms, moderate threshold; second pass: synonyms, permissive\n const originalResults = search(index, { term: originalTermsQuery, ...boostConfig, threshold: 0.8 });\n const expandedResults = search(index, { term: expandedQuery, ...boostConfig, threshold: 1 });\n\n type Hit = { score: number; document: { name: string } };\n const origHits = (originalResults as unknown as { hits: Hit[] }).hits;\n const expHits = (expandedResults as unknown as { hits: Hit[] }).hits;\n\n // Combine scores: original terms get 2x weight\n const scoreMap = new Map<string, number>();\n for (const hit of origHits) {\n scoreMap.set(hit.document.name, (hit.score || 0) * 2);\n }\n for (const hit of expHits) {\n const name = hit.document.name;\n const existing = scoreMap.get(name) ?? 0;\n scoreMap.set(name, existing + (hit.score || 0));\n }\n\n // Build a name→fragment lookup for status bonuses\n const fragmentMap = new Map<string, McpComponent>();\n for (const f of normalized) {\n fragmentMap.set(f.name.toLowerCase(), f);\n }\n\n // Exact name match bonus: if a component name matches an original query term exactly,\n // boost it above similar-named components (e.g., \"Button\" > \"ButtonGroup\" for \"button action\")\n const originalTermsSet = new Set(originalTermsList);\n\n // Build scored results with status + name match adjustments\n const scored: ScoredResult[] = [];\n for (const [name, rawScore] of scoreMap) {\n let score = rawScore;\n const nameLower = name.toLowerCase();\n const fragment = fragmentMap.get(nameLower);\n\n // Exact name match bonus — strong signal that this specific component was requested\n // Must be large enough to overcome BM25 score differences from compound names\n // (e.g., \"ButtonGroup\" matching more fields than \"Button\")\n if (originalTermsSet.has(nameLower)) {\n score += 25;\n }\n\n // Apply status bonus/penalty (matches old scorer)\n if (fragment) {\n if (fragment.status === 'stable') score += 5;\n else if (fragment.status === 'beta') score += 2;\n if (fragment.status === 'deprecated') score -= 25;\n }\n\n if (score > 0) {\n scored.push({ name, kind: 'component' as EntryKind, rank: scored.length, score });\n }\n }\n\n // Sort by score descending and assign ranks\n scored.sort((a, b) => b.score - a.score);\n scored.forEach((s, i) => { s.rank = i; });\n\n return scored;\n}\n\n// ---------------------------------------------------------------------------\n// Block index\n// ---------------------------------------------------------------------------\n\nconst blockSchema = {\n name: 'string' as const,\n description: 'string' as const,\n category: 'string' as const,\n tags: 'string' as const,\n components: 'string' as const,\n};\n\nexport type BlockIndex = AnyOrama;\n\nfunction normalizeBlock(value: McpBlock | CompiledBlock): McpBlock {\n if ('id' in value) return value;\n return {\n id: value.filePath ?? value.name,\n name: value.name,\n description: value.description ?? '',\n category: value.category ?? 'uncategorized',\n components: value.components ?? [],\n tags: value.tags ?? [],\n code: value.code ?? '',\n };\n}\n\nexport function buildBlockIndex(\n blocks: Array<McpBlock | CompiledBlock>,\n): BlockIndex {\n const db = create({ schema: blockSchema, language: 'english' });\n const normalized = blocks.map(normalizeBlock);\n\n const docs = normalized.map((b) => ({\n name: b.name,\n description: b.description ?? '',\n category: b.category ?? '',\n tags: (b.tags ?? []).join(' '),\n components: b.components.join(' '),\n }));\n\n insertMultiple(db, docs);\n return db;\n}\n\nexport function searchBlocks(\n query: string,\n index: BlockIndex,\n limit = 50,\n): ScoredResult[] {\n return twoPassSearch({\n index,\n query,\n properties: ['name', 'description', 'components', 'tags', 'category'],\n boost: {\n name: 3,\n description: 2,\n components: 1.5,\n tags: 1.5,\n category: 1.5,\n },\n limit,\n kind: 'block' as EntryKind,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Token index\n// ---------------------------------------------------------------------------\n\nconst tokenSchema = {\n name: 'string' as const,\n category: 'string' as const,\n description: 'string' as const,\n};\n\nexport type TokenIndex = AnyOrama;\n\nfunction normalizeTokenData(\n tokenData: McpTokenData | CompiledTokenData,\n): McpTokenData {\n if ('flat' in tokenData) return tokenData;\n const categories = Object.fromEntries(\n Object.entries(tokenData.categories).map(([category, entries]) => [\n category,\n entries.map((entry) => ({\n name: entry.name,\n category,\n value: typeof entry.value === 'string' ? entry.value : undefined,\n description: entry.description,\n })),\n ]),\n );\n return {\n prefix: tokenData.prefix,\n total: tokenData.total,\n categories,\n flat: Object.values(categories).flat(),\n };\n}\n\nexport function buildTokenIndex(\n tokenData: McpTokenData | CompiledTokenData,\n): TokenIndex {\n const db = create({ schema: tokenSchema, language: 'english' });\n const normalizedData = normalizeTokenData(tokenData);\n\n const docs: Array<{ name: string; category: string; description: string }> = [];\n for (const [cat, tokens] of Object.entries(normalizedData.categories) as Array<\n [string, McpTokenData['categories'][string]]\n >) {\n for (const token of tokens) {\n docs.push({\n name: token.name,\n category: cat,\n description: token.description ?? '',\n });\n }\n }\n\n insertMultiple(db, docs);\n return db;\n}\n\nexport function searchTokens(\n query: string,\n index: TokenIndex,\n limit = 50,\n): ScoredResult[] {\n return twoPassSearch({\n index,\n query,\n properties: ['name', 'category', 'description'],\n boost: {\n name: 2.5,\n category: 2,\n description: 1.5,\n },\n limit,\n kind: 'token' as EntryKind,\n });\n}\n\n// ---------------------------------------------------------------------------\n// Semantic category extraction for implement tool token matching\n// ---------------------------------------------------------------------------\n\n/** Maps use-case keywords to relevant token categories */\nexport const USE_CASE_TOKEN_CATEGORIES: Record<string, string[]> = {\n 'table': ['spacing', 'borders', 'surfaces', 'text'],\n 'data': ['spacing', 'borders', 'surfaces'],\n 'grid': ['spacing', 'layout'],\n 'form': ['spacing', 'borders', 'radius', 'focus'],\n 'input': ['spacing', 'borders', 'radius', 'focus'],\n 'card': ['surfaces', 'shadows', 'radius', 'borders', 'spacing'],\n 'button': ['colors', 'radius', 'spacing', 'focus'],\n 'layout': ['spacing', 'layout', 'surfaces'],\n 'dashboard': ['spacing', 'surfaces', 'borders', 'shadows'],\n 'chat': ['spacing', 'surfaces', 'radius', 'shadows'],\n 'modal': ['shadows', 'surfaces', 'radius', 'spacing'],\n 'dialog': ['shadows', 'surfaces', 'radius', 'spacing'],\n 'navigation': ['spacing', 'surfaces', 'borders'],\n 'sidebar': ['spacing', 'surfaces', 'borders'],\n 'hero': ['spacing', 'typography', 'colors'],\n 'landing': ['spacing', 'typography', 'colors'],\n 'pricing': ['spacing', 'surfaces', 'borders', 'radius'],\n 'auth': ['spacing', 'borders', 'radius', 'focus'],\n 'login': ['spacing', 'borders', 'radius', 'focus'],\n 'dark': ['colors', 'surfaces'],\n 'theme': ['colors', 'surfaces', 'text'],\n};\n\n/**\n * Extract relevant token categories from a use-case query.\n * Returns category names that should be included in implement results.\n */\nexport function extractTokenCategories(query: string): string[] {\n const terms = query.toLowerCase().split(/\\s+/).filter(Boolean);\n const categories = new Set<string>();\n\n for (const term of terms) {\n const cats = USE_CASE_TOKEN_CATEGORIES[term];\n if (cats) {\n for (const cat of cats) categories.add(cat);\n }\n }\n\n // If nothing matched, return common defaults\n if (categories.size === 0) {\n return ['spacing', 'colors', 'surfaces'];\n }\n\n return Array.from(categories);\n}\n","/**\n * Scoring utilities for MCP tool result ranking.\n *\n * Extracted as pure functions for easy testing and reuse across\n * discover, implement, and other search-driven tools.\n */\n\nimport type { ScoredResult } from './search.js';\n\n// ---------------------------------------------------------------------------\n// Confidence assignment — ratio-to-max (scale-independent)\n// ---------------------------------------------------------------------------\n\n/**\n * Minimum absolute score floor. If the best result scores below this,\n * results are considered a no-match rather than low-confidence garbage.\n *\n * BM25 scores for a 60-component corpus typically range 10-100+ for real\n * matches (including name-match bonuses of +25 and status bonuses of +5).\n * A maxScore below 5 means no meaningful term overlap was found — only\n * status bonuses and/or minimal synonym noise.\n *\n * Note: this threshold is calibrated for BM25 keyword scores. When hybrid\n * search uses RRF fusion (premium API key), scores are in a different range\n * (~0.01-0.05) and the threshold should be bypassed via a maxScore > 1 guard.\n */\nexport const MINIMUM_SCORE_THRESHOLD = 5;\n\n/**\n * Assign a confidence level based on how a score compares to the best result.\n *\n * Uses ratio-to-max instead of absolute thresholds so the same function works\n * for both keyword scores (8-50+) and RRF scores (0.01-0.02).\n *\n * - high: score >= 70% of maxScore (\"this is almost certainly what you need\")\n * - medium: score >= 40% of maxScore (\"this could be useful\")\n * - low: score < 40% of maxScore (\"tangentially related\")\n */\nexport function assignConfidence(\n score: number,\n maxScore: number,\n): 'high' | 'medium' | 'low' {\n if (maxScore <= 0) return 'low';\n const ratio = score / maxScore;\n if (ratio >= 0.7) return 'high';\n if (ratio >= 0.4) return 'medium';\n return 'low';\n}\n\n/**\n * Check if the best score in a result set meets the minimum quality threshold.\n * Returns true if results are meaningful, false if they're noise.\n */\nexport function meetsMinimumThreshold(maxScore: number): boolean {\n return maxScore >= MINIMUM_SCORE_THRESHOLD;\n}\n\n// ---------------------------------------------------------------------------\n// Levenshtein distance — for fuzzy \"did you mean?\" suggestions\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the Levenshtein edit distance between two strings.\n * Used for suggesting closest component name matches on typos.\n */\nexport function levenshtein(a: string, b: string): number {\n const la = a.length;\n const lb = b.length;\n const dp: number[] = Array.from({ length: lb + 1 }, (_, i) => i);\n\n for (let i = 1; i <= la; i++) {\n let prev = i - 1;\n dp[0] = i;\n for (let j = 1; j <= lb; j++) {\n const temp = dp[j];\n dp[j] = a[i - 1] === b[j - 1]\n ? prev\n : 1 + Math.min(prev, dp[j], dp[j - 1]);\n prev = temp;\n }\n }\n\n return dp[lb];\n}\n\n/**\n * Find the closest matching name from a list, using Levenshtein distance.\n * Returns the closest match if it's within `maxDistance`, or null otherwise.\n */\nexport function findClosestMatch(\n input: string,\n candidates: string[],\n maxDistance = 3,\n): string | null {\n const inputLower = input.toLowerCase();\n let bestMatch: string | null = null;\n let bestDist = maxDistance + 1;\n\n for (const candidate of candidates) {\n const candidateLower = candidate.toLowerCase();\n const dist = levenshtein(inputLower, candidateLower);\n if (dist < bestDist) {\n bestDist = dist;\n bestMatch = candidate;\n } else if (dist === bestDist && bestMatch) {\n // Tie-break: prefer the candidate whose length is closer to input length\n const currentLenDiff = Math.abs(bestMatch.length - input.length);\n const newLenDiff = Math.abs(candidate.length - input.length);\n if (newLenDiff < currentLenDiff) {\n bestMatch = candidate;\n }\n }\n }\n\n return bestDist <= maxDistance ? bestMatch : null;\n}\n\n// ---------------------------------------------------------------------------\n// Block-first component ranking\n// ---------------------------------------------------------------------------\n\n/** Points added per block occurrence (e.g., Card in 3 blocks → +15) */\nexport const BLOCK_BOOST_PER_OCCURRENCE = 5;\n\n/**\n * Count how many blocks each component appears in.\n *\n * Returns a Map<lowercase component name, count>.\n * This is the core signal for block-first ranking: if Card appears in 5/5\n * marketing blocks, it's clearly more important than Sidebar which appears in 0.\n */\nexport function buildBlockComponentFrequency(\n blocks: Array<{ components: string[] }>,\n): Map<string, number> {\n const freq = new Map<string, number>();\n for (const block of blocks) {\n for (const comp of block.components) {\n const key = comp.toLowerCase();\n freq.set(key, (freq.get(key) ?? 0) + 1);\n }\n }\n return freq;\n}\n\n/**\n * Boost component search results by how frequently they appear in matching blocks.\n *\n * Mutates scores in-place and re-sorts. Components that appear in more blocks\n * get a proportionally higher boost (freq * BLOCK_BOOST_PER_OCCURRENCE).\n *\n * Returns the mutated+sorted array for convenience.\n */\nexport function boostByBlockFrequency(\n results: ScoredResult[],\n freq: Map<string, number>,\n): ScoredResult[] {\n for (const result of results) {\n const count = freq.get(result.name.toLowerCase()) ?? 0;\n if (count > 0) {\n result.score += count * BLOCK_BOOST_PER_OCCURRENCE;\n }\n }\n results.sort((a, b) => b.score - a.score);\n results.forEach((r, i) => { r.rank = i; });\n return results;\n}\n","import { SYNONYM_MAP, USE_CASE_TOKEN_CATEGORIES } from './orama-index.js';\nimport { MINIMUM_SCORE_THRESHOLD, BLOCK_BOOST_PER_OCCURRENCE } from './scoring.js';\n\nexport interface SearchConfig {\n synonyms?: Record<string, string[]>;\n useCaseTokenCategories?: Record<string, string[]>;\n minimumScoreThreshold?: number;\n blockBoostPerOccurrence?: number;\n vectorSearchUrl?: string;\n vectorSearchTimeoutMs?: number;\n}\n\nexport const DEFAULT_SEARCH_CONFIG: Required<SearchConfig> = {\n synonyms: SYNONYM_MAP,\n useCaseTokenCategories: USE_CASE_TOKEN_CATEGORIES,\n minimumScoreThreshold: MINIMUM_SCORE_THRESHOLD,\n blockBoostPerOccurrence: BLOCK_BOOST_PER_OCCURRENCE,\n vectorSearchUrl: 'https://combative-jay-834.convex.site/search',\n vectorSearchTimeoutMs: 3000,\n};\n","// Server\nexport { createMcpServer, startMcpServer, createSandboxServer } from './server.js';\n\n// Types\nexport type { McpServerConfig, DesignSystemData, ToolHandler, ToolResult, ToolContext, SearchIndexes } from './types.js';\n\n// Registry\nexport { ToolRegistry } from './registry.js';\nexport type { ToolAvailability, AvailabilityContext } from './registry.js';\n\n// Middleware\nexport { executeWithMiddleware, telemetryMiddleware } from './middleware.js';\nexport type { Middleware, MiddlewareContext, MiddlewareNext } from './middleware.js';\n\n// Adapters\nexport type { DataAdapter } from './adapters/types.js';\nexport { FragmentsJsonAdapter } from './adapters/fragments-json.js';\nexport { CustomJsonAdapter } from './adapters/custom-json.js';\nexport { AutoExtractionAdapter } from './adapters/auto-extract.js';\n\n// Config\nexport { loadConfigFile } from './config.js';\nexport type { DsMcpConfigFile } from './config.js';\n\n// Rules generation\nexport { generateRulesFiles } from './rules.js';\nexport type { RulesFormat, RulesGeneratorOptions } from './rules.js';\n\n// Search config\nexport type { SearchConfig } from './search-config.js';\nexport { DEFAULT_SEARCH_CONFIG } from './search-config.js';\n\n// Tool sets\nexport { BUILTIN_TOOLS, CORE_TOOLS, VIEWER_TOOLS, INFRA_TOOLS } from './tools/index.js';\n\n// Constants\nexport { BRAND } from '@fragments-sdk/core';\nexport type { Brand } from '@fragments-sdk/core';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,yBAA2C;AAiB7C,IAAM,oBAAN,MAA+C;AAAA,EAGpD,YAAoB,UAAkB;AAAlB;AAAA,EAAmB;AAAA,EAAnB;AAAA,EAFX,OAAO;AAAA,EAIhB,WAAqB;AACnB,WAAO,WAAW,KAAK,QAAQ,IAAI,CAAC,KAAK,QAAQ,IAAI,CAAC;AAAA,EACxD;AAAA,EAEA,MAAM,KAAK,eAAe,IAA+B;AACvD,QAAI,CAAC,WAAW,KAAK,QAAQ,GAAG;AAC9B,YAAM,IAAI,MAAM,+BAA+B,KAAK,QAAQ,EAAE;AAAA,IAChE;AAEA,UAAM,UAAU,MAAM,SAAS,KAAK,UAAU,OAAO;AACrD,UAAM,MAAM,KAAK,MAAM,OAAO;AAE9B,QACE,IAAI,kBAAkB,KACtB,OAAO,IAAI,eAAe,YAC1B,IAAI,cACJ,OAAO,IAAI,eAAe,UAC1B;AACA,YAAMA,YAAW,kBAAkB,MAAM,GAAG;AAC5C,aAAO;AAAA,QACL,UAAAA;AAAA,QACA,YAAYA,UAAS;AAAA,QACrB,QAAQA,UAAS;AAAA,QACjB,QAAQA,UAAS;AAAA,QACjB,OAAOA,UAAS;AAAA,QAChB,oBAAoBA,UAAS;AAAA,QAC7B,YAAYA,UAAS;AAAA,QACrB,oBAAoBA,UAAS;AAAA,QAC7B,cAAc,IAAI,IAAIA,UAAS,YAAY;AAAA,MAC7C;AAAA,I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,EAC1C,aAAa,CAAC,WAAW,YAAY,WAAW,SAAS;AAAA,EACzD,QAAQ,CAAC,WAAW,YAAY,UAAU,SAAS;AAAA,EACnD,SAAS,CAAC,WAAW,YAAY,UAAU,SAAS;AAAA,EACpD,UAAU,CAAC,WAAW,YAAY,UAAU,SAAS;AAAA,EACrD,cAAc,CAAC,WAAW,YAAY,SAAS;AAAA,EAC/C,WAAW,CAAC,WAAW,YAAY,SAAS;AAAA,EAC5C,QAAQ,CAAC,WAAW,cAAc,QAAQ;AAAA,EAC1C,WAAW,CAAC,WAAW,cAAc,QAAQ;AAAA,EAC7C,WAAW,CAAC,WAAW,YAAY,WAAW,QAAQ;AAAA,EACtD,QAAQ,CAAC,WAAW,WAAW,UAAU,OAAO;AAAA,EAChD,SAAS,CAAC,WAAW,WAAW,UAAU,OAAO;AAAA,EACjD,QAAQ,CAAC,UAAU,UAAU;AAAA,EAC7B,SAAS,CAAC,UAAU,YAAY,MAAM;AACxC;;;AC7dO,IAAM,0BAA0B;AAgGhC,IAAM,6BAA6B;;;AC9GnC,IAAM,wBAAgD;AAAA,EAC3D,UAAU;AAAA,EACV,wBAAwB;AAAA,EACxB,uBAAuB;AAAA,EACvB,yBAAyB;AAAA,EACzB,iBAAiB;AAAA,EACjB,uBAAuB;AACzB;;;ACiBA,SAAS,aAAa;","names":["snapshot"]}
|
|
1
|
+
{"version":3,"sources":["../src/apps/resources.ts","../src/tasks/store.ts","../src/spec/generated/schema.ts","../src/tools/primitives.ts","../src/tools/conform.ts","../src/tools/prove-compliant-schema.ts","../src/tools/prove-compliant.ts","../src/tools/registry.ts","../src/protocol/server.ts","../src/testing/fixtures.ts"],"sourcesContent":["import type { ResourceDefinition } from \"../types.js\";\n\nexport const MCP_APP_RESOURCES: ResourceDefinition[] = [];\n\nexport function getResource(_uri: string): ResourceDefinition | null {\n return null;\n}\n\nexport function listResources() {\n return [];\n}\n","import type { TaskRecord, TaskStore, ToolResult } from \"../types.js\";\n\nlet nextTaskId = 1;\n\nfunction createTaskId() {\n const id = `task_${String(nextTaskId).padStart(6, \"0\")}`;\n nextTaskId += 1;\n return id;\n}\n\nexport class MemoryTaskStore implements TaskStore {\n private readonly tasks = new Map<string, TaskRecord>();\n\n async create(input: {\n title: string;\n ttlMs?: number;\n pollIntervalMs?: number;\n result?: ToolResult;\n workflow?: {\n kind: string;\n arguments?: Record<string, unknown>;\n };\n }): Promise<TaskRecord> {\n const now = Date.now();\n const result = input.result ?? completedWorkflowResult(input.workflow?.kind);\n const task: TaskRecord = {\n taskId: createTaskId(),\n title: input.title,\n status: result ? \"completed\" : \"working\",\n createdAt: now,\n updatedAt: now,\n ttlMs: input.ttlMs ?? 15 * 60 * 1000,\n pollIntervalMs: input.pollIntervalMs ?? 1000,\n result,\n progress: result\n ? { current: 1, total: 1, message: \"Completed\" }\n : { current: 0, total: 1, message: \"Queued\" },\n };\n\n this.tasks.set(task.taskId, task);\n return task;\n }\n\n async get(taskId: string): Promise<TaskRecord | null> {\n return this.tasks.get(taskId) ?? null;\n }\n\n async update(taskId: string, patch: Partial<TaskRecord>): Promise<TaskRecord | null> {\n const existing = this.tasks.get(taskId);\n if (!existing) return null;\n\n const next: TaskRecord = {\n ...existing,\n ...patch,\n taskId,\n updatedAt: Date.now(),\n };\n this.tasks.set(taskId, next);\n return next;\n }\n\n async cancel(taskId: string): Promise<TaskRecord | null> {\n return this.update(taskId, {\n status: \"cancelled\",\n progress: { message: \"Cancellation requested\" },\n });\n }\n}\n\nfunction completedWorkflowResult(kind?: string): ToolResult | undefined {\n if (!kind) return undefined;\n return {\n content: [{ type: \"text\", text: `${kind} queued.` }],\n structuredContent: {\n kind,\n status: \"queued\",\n message:\n \"Fragments accepted the workflow request. The hosted runtime attaches concrete job details.\",\n },\n };\n}\n","/* JSON types */\n\n/**\n * @category Common Types\n */\nexport type JSONValue =\n | string\n | number\n | boolean\n | null\n | JSONObject\n | JSONArray;\n\n/**\n * @category Common Types\n */\nexport type JSONObject = { [key: string]: JSONValue };\n\n/**\n * @category Common Types\n */\nexport type JSONArray = JSONValue[];\n\n/* JSON-RPC types */\n\n/**\n * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.\n *\n * @category JSON-RPC\n */\nexport type JSONRPCMessage =\n | JSONRPCRequest\n | JSONRPCNotification\n | JSONRPCResponse;\n\n/** @internal */\nexport const LATEST_PROTOCOL_VERSION = \"DRAFT-2026-v1\";\n/** @internal */\nexport const JSONRPC_VERSION = \"2.0\";\n\n/**\n * Represents the contents of a `_meta` field, which clients and servers use to attach additional metadata to their interactions.\n *\n * Certain key names are reserved by MCP for protocol-level metadata; implementations MUST NOT make assumptions about values at these keys. Additionally, specific schema definitions may reserve particular names for purpose-specific metadata, as declared in those definitions.\n *\n * Valid keys have two segments:\n *\n * **Prefix:**\n * - Optional — if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`).\n * - Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`).\n * - Implementations SHOULD use reverse DNS notation (e.g., `com.example/` rather than `example.com/`).\n * - Any prefix where the second label is `modelcontextprotocol` or `mcp` is **reserved** for MCP use. For example: `io.modelcontextprotocol/`, `dev.mcp/`, `org.modelcontextprotocol.api/`, and `com.mcp.tools/` are all reserved. However, `com.example.mcp/` is NOT reserved, as the second label is `example`.\n *\n * **Name:**\n * - Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`).\n * - Interior characters may be alphanumeric, hyphens (`-`), underscores (`_`), or dots (`.`).\n *\n * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details.\n * @category Common Types\n */\nexport type MetaObject = Record<string, unknown>;\n\n/**\n * Extends {@link MetaObject} with additional request-specific fields. All key naming rules from `MetaObject` apply.\n *\n * @see {@link MetaObject} for key naming rules and reserved prefixes.\n * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details.\n * @category Common Types\n */\nexport interface RequestMetaObject extends MetaObject {\n /**\n * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by {@link ProgressNotification | notifications/progress}). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.\n */\n progressToken?: ProgressToken;\n /**\n * The MCP Protocol Version being used for this request. Required.\n *\n * For the HTTP transport, this value MUST match the `MCP-Protocol-Version`\n * header; otherwise the server MUST return a `400 Bad Request`. If the\n * server does not support the requested version, it MUST return an\n * {@link UnsupportedProtocolVersionError}.\n */\n \"io.modelcontextprotocol/protocolVersion\": string;\n /**\n * Identifies the client software making the request. Required.\n *\n * The {@link Implementation} schema requires `name` and `version`; other\n * fields are optional.\n */\n \"io.modelcontextprotocol/clientInfo\": Implementation;\n /**\n * The client's capabilities for this specific request. Required.\n *\n * Capabilities are declared per-request rather than once at initialization;\n * an empty object means the client supports no optional capabilities.\n * Servers MUST NOT infer capabilities from prior requests.\n */\n \"io.modelcontextprotocol/clientCapabilities\": ClientCapabilities;\n /**\n * The desired log level for this request. Optional.\n *\n * If absent, the server MUST NOT send any {@link LoggingMessageNotification | notifications/message}\n * notifications for this request. The client opts in to log messages by\n * explicitly setting a level. Replaces the former `logging/setLevel` RPC.\n */\n \"io.modelcontextprotocol/logLevel\"?: LoggingLevel;\n}\n\n/**\n * A progress token, used to associate progress notifications with the original request.\n *\n * @category Common Types\n */\nexport type ProgressToken = string | number;\n\n/**\n * An opaque token used to represent a cursor for pagination.\n *\n * @category Common Types\n */\nexport type Cursor = string;\n\n/**\n * Common params for any request.\n *\n * @category Common Types\n */\nexport interface RequestParams {\n _meta: RequestMetaObject;\n}\n\n/** @internal */\nexport interface Request {\n method: string;\n // Allow unofficial extensions of `Request.params` without impacting `RequestParams`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params?: { [key: string]: any };\n}\n\n/**\n * Common params for any notification.\n *\n * @category Common Types\n */\nexport interface NotificationParams {\n _meta?: MetaObject;\n}\n\n/** @internal */\nexport interface Notification {\n method: string;\n // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n params?: { [key: string]: any };\n}\n\n/**\n * Indicates the type of a {@link Result} object, allowing the client to\n * determine how to parse the response.\n *\n * complete - the request completed successfully and the result contains the final content.\n * input_required - the request requires additional input and the result contains an {@link InputRequiredResult} object with instructions for the client to provide additional input before retrying the original request.\n * @category Common Types\n */\nexport type ResultType = \"complete\" | \"input_required\";\n\n/**\n * Common result fields.\n *\n * @category Common Types\n */\nexport interface Result {\n _meta?: MetaObject;\n /**\n * Indicates the type of the result, which allows the client to determine\n * how to parse the result object.\n *\n * Servers implementing this protocol version MUST include this field.\n * For backward compatibility, when a client receives a result from a\n * server implementing an earlier protocol version (which does not include\n * `resultType`), the client MUST treat the absent field as `\"complete\"`.\n */\n resultType: ResultType;\n [key: string]: unknown;\n}\n\n/**\n * @category Errors\n */\nexport interface Error {\n /**\n * The error type that occurred.\n */\n code: number;\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: string;\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data?: unknown;\n}\n\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n *\n * @category Common Types\n */\nexport type RequestId = string | number;\n\n/**\n * A request that expects a response.\n *\n * @category JSON-RPC\n */\nexport interface JSONRPCRequest extends Request {\n jsonrpc: typeof JSONRPC_VERSION;\n id: RequestId;\n}\n\n/**\n * A notification which does not expect a response.\n *\n * @category JSON-RPC\n */\nexport interface JSONRPCNotification extends Notification {\n jsonrpc: typeof JSONRPC_VERSION;\n}\n\n/**\n * A successful (non-error) response to a request.\n *\n * @category JSON-RPC\n */\nexport interface JSONRPCResultResponse {\n jsonrpc: typeof JSONRPC_VERSION;\n id: RequestId;\n result: Result;\n}\n\n/**\n * A response to a request that indicates an error occurred.\n *\n * @category JSON-RPC\n */\nexport interface JSONRPCErrorResponse {\n jsonrpc: typeof JSONRPC_VERSION;\n id?: RequestId;\n error: Error;\n}\n\n/**\n * A response to a request, containing either the result or error.\n *\n * @category JSON-RPC\n */\nexport type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse;\n\n// Standard JSON-RPC error codes\nexport const PARSE_ERROR = -32700;\nexport const INVALID_REQUEST = -32600;\nexport const METHOD_NOT_FOUND = -32601;\nexport const INVALID_PARAMS = -32602;\nexport const INTERNAL_ERROR = -32603;\n\n/**\n * A JSON-RPC error indicating that invalid JSON was received by the server. This error is returned when the server cannot parse the JSON text of a message.\n *\n * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}\n *\n * @example Invalid JSON\n * {@includeCode ./examples/ParseError/invalid-json.json}\n *\n * @category Errors\n */\nexport interface ParseError extends Error {\n code: typeof PARSE_ERROR;\n}\n\n/**\n * A JSON-RPC error indicating that the request is not a valid request object. This error is returned when the message structure does not conform to the JSON-RPC 2.0 specification requirements for a request (e.g., missing required fields like `jsonrpc` or `method`, or using invalid types for these fields).\n *\n * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}\n *\n * @category Errors\n */\nexport interface InvalidRequestError extends Error {\n code: typeof INVALID_REQUEST;\n}\n\n/**\n * A JSON-RPC error indicating that the requested method does not exist or is not available.\n *\n * In MCP, this error is returned when a request is made for a method that requires a capability that has not been declared. This can occur in either direction:\n *\n * - A server returning this error when the client requests a capability it doesn't support (e.g., requesting completions when the `completions` capability was not advertised)\n * - A client returning this error when the server requests a capability it doesn't support (e.g., requesting roots when the client did not declare the `roots` capability)\n *\n * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}\n *\n * @example Roots not supported\n * {@includeCode ./examples/MethodNotFoundError/roots-not-supported.json}\n *\n * @category Errors\n */\nexport interface MethodNotFoundError extends Error {\n code: typeof METHOD_NOT_FOUND;\n}\n\n/**\n * A JSON-RPC error indicating that the method parameters are invalid or malformed.\n *\n * In MCP, this error is returned in various contexts when request parameters fail validation:\n *\n * - **Tools**: Unknown tool name or invalid tool arguments\n * - **Prompts**: Unknown prompt name or missing required arguments\n * - **Pagination**: Invalid or expired cursor values\n * - **Logging**: Invalid log level\n * - **Elicitation**: Server requests an elicitation mode not declared in client capabilities\n * - **Sampling**: Missing tool result or tool results mixed with other content\n *\n * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}\n *\n * @example Unknown tool\n * {@includeCode ./examples/InvalidParamsError/unknown-tool.json}\n *\n * @example Invalid tool arguments\n * {@includeCode ./examples/InvalidParamsError/invalid-tool-arguments.json}\n *\n * @example Unknown prompt\n * {@includeCode ./examples/InvalidParamsError/unknown-prompt.json}\n *\n * @example Invalid cursor\n * {@includeCode ./examples/InvalidParamsError/invalid-cursor.json}\n *\n * @category Errors\n */\nexport interface InvalidParamsError extends Error {\n code: typeof INVALID_PARAMS;\n}\n\n/**\n * A JSON-RPC error indicating that an internal error occurred on the receiver. This error is returned when the receiver encounters an unexpected condition that prevents it from fulfilling the request.\n *\n * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}\n *\n * @example Unexpected error\n * {@includeCode ./examples/InternalError/unexpected-error.json}\n *\n * @category Errors\n */\nexport interface InternalError extends Error {\n code: typeof INTERNAL_ERROR;\n}\n\n/**\n * Error code returned when a server requires a client capability that was\n * not declared in the request's `clientCapabilities`.\n *\n * @category Errors\n */\nexport const MISSING_REQUIRED_CLIENT_CAPABILITY = -32003;\n\n/**\n * Error code returned when the request's protocol version is not supported\n * by the server.\n *\n * @category Errors\n */\nexport const UNSUPPORTED_PROTOCOL_VERSION = -32004;\n\n/**\n * Returned when the request's protocol version is unknown to the server or\n * unsupported (e.g., a known experimental or draft version the server has\n * chosen not to implement). For HTTP, the response status code MUST be\n * `400 Bad Request`.\n *\n * @example Unsupported protocol version\n * {@includeCode ./examples/UnsupportedProtocolVersionError/unsupported-version.json}\n *\n * @category Errors\n */\nexport interface UnsupportedProtocolVersionError extends Omit<\n JSONRPCErrorResponse,\n \"error\"\n> {\n error: Error & {\n code: typeof UNSUPPORTED_PROTOCOL_VERSION;\n data: {\n /**\n * Protocol versions the server supports. The client should choose a\n * mutually supported version from this list and retry.\n */\n supported: string[];\n /**\n * The protocol version that was requested by the client.\n */\n requested: string;\n };\n };\n}\n\n/**\n * Returned when processing a request requires a capability the client did not\n * declare in `clientCapabilities`. For HTTP, the response status code MUST be\n * `400 Bad Request`.\n *\n * @example Missing elicitation capability\n * {@includeCode ./examples/MissingRequiredClientCapabilityError/missing-elicitation-capability.json}\n *\n * @category Errors\n */\nexport interface MissingRequiredClientCapabilityError extends Omit<\n JSONRPCErrorResponse,\n \"error\"\n> {\n error: Error & {\n code: typeof MISSING_REQUIRED_CLIENT_CAPABILITY;\n data: {\n /**\n * The capabilities the server requires from the client to process this request.\n */\n requiredCapabilities: ClientCapabilities;\n };\n };\n}\n\n/* Empty result */\n/**\n * A result that indicates success but carries no data.\n *\n * @category Common Types\n */\nexport type EmptyResult = Result;\n\n/** @internal */\nexport type InputRequest =\n | CreateMessageRequest\n | ListRootsRequest\n | ElicitRequest;\n\n/** @internal */\nexport type InputResponse =\n | CreateMessageResult\n | ListRootsResult\n | ElicitResult;\n\n/**\n * A map of server-initiated requests that the client must fulfill.\n * Keys are server-assigned identifiers; values are the request objects.\n *\n * @example Elicitation and sampling input requests\n * {@includeCode ./examples/InputRequests/elicitation-and-sampling-input-requests.json}\n *\n * @category Multi Round-Trip\n */\nexport interface InputRequests {\n [key: string]: InputRequest;\n}\n\n/**\n * A map of client responses to server-initiated requests.\n * Keys correspond to the keys in the {@link InputRequests} map;\n * values are the client's result for each request.\n *\n * @example Elicitation and sampling input responses\n * {@includeCode ./examples/InputResponses/elicitation-and-sampling-input-responses.json}\n *\n * @category Multi Round-Trip\n */\nexport interface InputResponses {\n [key: string]: InputResponse;\n}\n\n/**\n * An InputRequiredResult sent by the server to indicate that additional input is needed\n * before the request can be completed.\n *\n * At least one of `inputRequests` or `requestState` MUST be present.\n * @example InputRequiredResult with elicitation and sampling input requests and request state\n * {@includeCode ./examples/InputRequiredResult/input-required-result-with-elicitation-and-sampling-and-request-state.json}\n *\n * @example InputRequiredResult with request state only (load shedding)\n * {@includeCode ./examples/InputRequiredResult/input-required-result-with-request-state-only.json}\n *\n * @category Multi Round-Trip\n */\nexport interface InputRequiredResult extends Result {\n /* Requests issued by the server that must be complete before the\n * client can retry the original request.\n */\n inputRequests?: InputRequests;\n /* Request state to be passed back to the server when the client\n * retries the original request.\n * Note: The client must treat this as an opaque blob; it must not\n * interpret it in any way.\n */\n requestState?: string;\n}\n\n/* Request parameter type that includes input responses and request state.\n * These parameters may be included in any client-initiated request.\n */\nexport interface InputResponseRequestParams extends RequestParams {\n /* New field to carry the responses for the server's requests from the\n * InputRequiredResult message. For each key in the response's inputRequests\n * field, the same key must appear here with the associated response.\n */\n inputResponses?: InputResponses;\n /* Request state passed back to the server from the client.\n */\n requestState?: string;\n}\n\n/* Cancellation */\n/**\n * Parameters for a `notifications/cancelled` notification.\n *\n * @example User-requested cancellation\n * {@includeCode ./examples/CancelledNotificationParams/user-requested-cancellation.json}\n *\n * @category `notifications/cancelled`\n */\nexport interface CancelledNotificationParams extends NotificationParams {\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId?: RequestId;\n\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason?: string;\n}\n\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * @example User-requested cancellation\n * {@includeCode ./examples/CancelledNotification/user-requested-cancellation.json}\n *\n * @category `notifications/cancelled`\n */\nexport interface CancelledNotification extends JSONRPCNotification {\n method: \"notifications/cancelled\";\n params: CancelledNotificationParams;\n}\n\n/* Discovery */\n/**\n * A request from the client asking the server to advertise its supported\n * protocol versions, capabilities, and other metadata. Servers **MUST**\n * implement `server/discover`. Clients **MAY** call it but are not required\n * to — version negotiation can also happen inline via per-request `_meta`.\n *\n * @example Discover request\n * {@includeCode ./examples/DiscoverRequest/server-discover-request.json}\n *\n * @category `server/discover`\n */\nexport interface DiscoverRequest extends JSONRPCRequest {\n method: \"server/discover\";\n params: RequestParams;\n}\n\n/**\n * The result returned by the server for a {@link DiscoverRequest | server/discover} request.\n *\n * @example Server capabilities discovery\n * {@includeCode ./examples/DiscoverResult/server-capabilities-discovery.json}\n *\n * @category `server/discover`\n */\nexport interface DiscoverResult extends Result {\n /**\n * MCP Protocol Versions this server supports. The client should choose a\n * version from this list for use in subsequent requests.\n */\n supportedVersions: string[];\n /**\n * The capabilities of the server.\n */\n capabilities: ServerCapabilities;\n /**\n * Information about the server software implementation.\n */\n serverInfo: Implementation;\n /**\n * Natural-language guidance describing the server and its features.\n *\n * This can be used by clients to improve an LLM's understanding of\n * available tools (e.g., by including it in a system prompt). It should\n * focus on information that helps the model use the server effectively\n * and should not duplicate information already in tool descriptions.\n */\n instructions?: string;\n}\n\n/**\n * A successful response from the server for a {@link DiscoverRequest | server/discover} request.\n *\n * @example Discover result response\n * {@includeCode ./examples/DiscoverResultResponse/discover-result-response.json}\n *\n * @category `server/discover`\n */\nexport interface DiscoverResultResponse extends JSONRPCResultResponse {\n result: DiscoverResult;\n}\n\n/**\n * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.\n *\n * @category `server/discover`\n */\nexport interface ClientCapabilities {\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental?: { [key: string]: JSONObject };\n /**\n * Present if the client supports listing roots.\n *\n * @example Roots — minimum baseline support\n * {@includeCode ./examples/ClientCapabilities/roots-minimum-baseline-support.json}\n */\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n roots?: {};\n /**\n * Present if the client supports sampling from an LLM.\n *\n * @example Sampling — minimum baseline support\n * {@includeCode ./examples/ClientCapabilities/sampling-minimum-baseline-support.json}\n *\n * @example Sampling — tool use support\n * {@includeCode ./examples/ClientCapabilities/sampling-tool-use-support.json}\n *\n * @example Sampling — context inclusion support (soft-deprecated)\n * {@includeCode ./examples/ClientCapabilities/sampling-context-inclusion-support-soft-deprecated.json}\n */\n sampling?: {\n /**\n * Whether the client supports context inclusion via `includeContext` parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context?: JSONObject;\n /**\n * Whether the client supports tool use via `tools` and `toolChoice` parameters.\n */\n tools?: JSONObject;\n };\n /**\n * Present if the client supports elicitation from the server.\n *\n * @example Elicitation — form and URL mode support\n * {@includeCode ./examples/ClientCapabilities/elicitation-form-and-url-mode-support.json}\n *\n * @example Elicitation — form mode only (implicit)\n * {@includeCode ./examples/ClientCapabilities/elicitation-form-only-implicit.json}\n */\n elicitation?: {\n form?: JSONObject;\n url?: JSONObject;\n };\n\n /**\n * Optional MCP extensions that the client supports. Keys are extension identifiers\n * (e.g., \"io.modelcontextprotocol/oauth-client-credentials\"), and values are\n * per-extension settings objects. An empty object indicates support with no settings.\n *\n * @example Extensions — UI extension with MIME type support\n * {@includeCode ./examples/ClientCapabilities/extensions-ui-mime-types.json}\n */\n extensions?: { [key: string]: JSONObject };\n}\n\n/**\n * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.\n *\n * @category `server/discover`\n */\nexport interface ServerCapabilities {\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental?: { [key: string]: JSONObject };\n /**\n * Present if the server supports sending log messages to the client.\n *\n * @example Logging — minimum baseline support\n * {@includeCode ./examples/ServerCapabilities/logging-minimum-baseline-support.json}\n */\n logging?: JSONObject;\n /**\n * Present if the server supports argument autocompletion suggestions.\n *\n * @example Completions — minimum baseline support\n * {@includeCode ./examples/ServerCapabilities/completions-minimum-baseline-support.json}\n */\n completions?: JSONObject;\n /**\n * Present if the server offers any prompt templates.\n *\n * @example Prompts — minimum baseline support\n * {@includeCode ./examples/ServerCapabilities/prompts-minimum-baseline-support.json}\n *\n * @example Prompts — list changed notifications\n * {@includeCode ./examples/ServerCapabilities/prompts-list-changed-notifications.json}\n */\n prompts?: {\n /**\n * Whether this server supports notifications for changes to the prompt list.\n */\n listChanged?: boolean;\n };\n /**\n * Present if the server offers any resources to read.\n *\n * @example Resources — minimum baseline support\n * {@includeCode ./examples/ServerCapabilities/resources-minimum-baseline-support.json}\n *\n * @example Resources — subscription to individual resource updates (only)\n * {@includeCode ./examples/ServerCapabilities/resources-subscription-to-individual-resource-updates-only.json}\n *\n * @example Resources — list changed notifications (only)\n * {@includeCode ./examples/ServerCapabilities/resources-list-changed-notifications-only.json}\n *\n * @example Resources — all notifications\n * {@includeCode ./examples/ServerCapabilities/resources-all-notifications.json}\n */\n resources?: {\n /**\n * Whether this server supports subscribing to resource updates.\n */\n subscribe?: boolean;\n /**\n * Whether this server supports notifications for changes to the resource list.\n */\n listChanged?: boolean;\n };\n /**\n * Present if the server offers any tools to call.\n *\n * @example Tools — minimum baseline support\n * {@includeCode ./examples/ServerCapabilities/tools-minimum-baseline-support.json}\n *\n * @example Tools — list changed notifications\n * {@includeCode ./examples/ServerCapabilities/tools-list-changed-notifications.json}\n */\n tools?: {\n /**\n * Whether this server supports notifications for changes to the tool list.\n */\n listChanged?: boolean;\n };\n /**\n * Optional MCP extensions that the server supports. Keys are extension identifiers\n * (e.g., \"io.modelcontextprotocol/apps\"), and values are per-extension settings\n * objects. An empty object indicates support with no settings.\n *\n * @example Extensions — UI extension support\n * {@includeCode ./examples/ServerCapabilities/extensions-ui.json}\n */\n extensions?: { [key: string]: JSONObject };\n}\n\n/**\n * An optionally-sized icon that can be displayed in a user interface.\n *\n * @category Common Types\n */\nexport interface Icon {\n /**\n * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a\n * `data:` URI with Base64-encoded image data.\n *\n * Consumers SHOULD take steps to ensure URLs serving icons are from the\n * same domain as the client/server or a trusted domain.\n *\n * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain\n * executable JavaScript.\n *\n * @format uri\n */\n src: string;\n\n /**\n * Optional MIME type override if the source MIME type is missing or generic.\n * For example: `\"image/png\"`, `\"image/jpeg\"`, or `\"image/svg+xml\"`.\n */\n mimeType?: string;\n\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes?: string[];\n\n /**\n * Optional specifier for the theme this icon is designed for. `\"light\"` indicates\n * the icon is designed to be used with a light background, and `\"dark\"` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme?: \"light\" | \"dark\";\n}\n\n/**\n * Base interface to add `icons` property.\n *\n * @internal\n */\nexport interface Icons {\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons?: Icon[];\n}\n\n/**\n * Base interface for metadata with name (identifier) and title (display name) properties.\n *\n * @internal\n */\nexport interface BaseMetadata {\n /**\n * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).\n */\n name: string;\n\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for {@link Tool},\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title?: string;\n}\n\n/**\n * Describes the MCP implementation.\n *\n * @category `server/discover`\n */\nexport interface Implementation extends BaseMetadata, Icons {\n /**\n * The version of this implementation.\n */\n version: string;\n\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description?: string;\n\n /**\n * An optional URL of the website for this implementation.\n *\n * @format uri\n */\n websiteUrl?: string;\n}\n\n/* Progress notifications */\n\n/**\n * Parameters for a {@link ProgressNotification | notifications/progress} notification.\n *\n * @example Progress message\n * {@includeCode ./examples/ProgressNotificationParams/progress-message.json}\n *\n * @category `notifications/progress`\n */\nexport interface ProgressNotificationParams extends NotificationParams {\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressToken;\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n *\n * @TJS-type number\n */\n progress: number;\n /**\n * Total number of items to process (or total progress required), if known.\n *\n * @TJS-type number\n */\n total?: number;\n /**\n * An optional message describing the current progress.\n */\n message?: string;\n}\n\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @example Progress message\n * {@includeCode ./examples/ProgressNotification/progress-message.json}\n *\n * @category `notifications/progress`\n */\nexport interface ProgressNotification extends JSONRPCNotification {\n method: \"notifications/progress\";\n params: ProgressNotificationParams;\n}\n\n/* Pagination */\n/**\n * Common params for paginated requests.\n *\n * @example List request with cursor\n * {@includeCode ./examples/PaginatedRequestParams/list-with-cursor.json}\n *\n * @category Common Types\n */\nexport interface PaginatedRequestParams extends RequestParams {\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor?: Cursor;\n}\n\n/** @internal */\nexport interface PaginatedRequest extends JSONRPCRequest {\n params: PaginatedRequestParams;\n}\n\n/** @internal */\nexport interface PaginatedResult extends Result {\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor?: Cursor;\n}\n\n/**\n * A result that supports a time-to-live (TTL) hint for client-side caching.\n *\n * @internal\n */\nexport interface CacheableResult extends Result {\n /**\n * A hint from the server indicating how long (in milliseconds) the\n * client MAY cache this response before re-fetching. Semantics are\n * analogous to HTTP Cache-Control max-age.\n *\n * - If 0, The response SHOULD be considered immediately stale,\n * The client MAY re-fetch every time the result is needed.\n * - If positive, the client SHOULD consider the result fresh for this many\n * milliseconds after receiving the response.\n *\n * @minimum 0\n */\n ttlMs: number;\n\n /**\n * Indicates the intended scope of the cached response, analogous to HTTP\n * `Cache-Control: public` vs `Cache-Control: private`.\n *\n * - `\"public\"`: Any client or intermediary (e.g., shared gateway, proxy)\n * MAY cache the response and serve it to any user.\n * - `\"private\"`: Only the requesting user's client MAY cache the response.\n * Shared caches (e.g., multi-tenant gateways) MUST NOT serve a cached\n * copy to a different user.\n *\n */\n cacheScope: \"public\" | \"private\";\n}\n\n/* Resources */\n/**\n * Sent from the client to request a list of resources the server has.\n *\n * @example List resources request\n * {@includeCode ./examples/ListResourcesRequest/list-resources-request.json}\n *\n * @category `resources/list`\n */\nexport interface ListResourcesRequest extends PaginatedRequest {\n method: \"resources/list\";\n}\n\n/**\n * The result returned by the server for a {@link ListResourcesRequest | resources/list} request.\n *\n * @example Resources list with cursor and TTL\n * {@includeCode ./examples/ListResourcesResult/resources-list-with-cursor-and-ttl.json}\n *\n * @category `resources/list`\n */\nexport interface ListResourcesResult extends PaginatedResult, CacheableResult {\n resources: Resource[];\n}\n\n/**\n * A successful response from the server for a {@link ListResourcesRequest | resources/list} request.\n *\n * @example List resources result response\n * {@includeCode ./examples/ListResourcesResultResponse/list-resources-result-response.json}\n *\n * @category `resources/list`\n */\nexport interface ListResourcesResultResponse extends JSONRPCResultResponse {\n result: ListResourcesResult;\n}\n\n/**\n * Sent from the client to request a list of resource templates the server has.\n *\n * @example List resource templates request\n * {@includeCode ./examples/ListResourceTemplatesRequest/list-resource-templates-request.json}\n *\n * @category `resources/templates/list`\n */\nexport interface ListResourceTemplatesRequest extends PaginatedRequest {\n method: \"resources/templates/list\";\n}\n\n/**\n * The result returned by the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request.\n *\n * @example Resource templates list with cursor and TTL\n * {@includeCode ./examples/ListResourceTemplatesResult/resource-templates-list-with-cursor-and-ttl.json}\n *\n * @category `resources/templates/list`\n */\nexport interface ListResourceTemplatesResult\n extends PaginatedResult, CacheableResult {\n resourceTemplates: ResourceTemplate[];\n}\n\n/**\n * A successful response from the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request.\n *\n * @example List resource templates result response\n * {@includeCode ./examples/ListResourceTemplatesResultResponse/list-resource-templates-result-response.json}\n *\n * @category `resources/templates/list`\n */\nexport interface ListResourceTemplatesResultResponse extends JSONRPCResultResponse {\n result: ListResourceTemplatesResult;\n}\n\n/**\n * Common params for resource-related requests.\n *\n * @internal\n */\nexport interface ResourceRequestParams extends RequestParams {\n /**\n * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: string;\n}\n\n/**\n * Parameters for a `resources/read` request.\n *\n * @category `resources/read`\n */\nexport interface ReadResourceRequestParams\n extends ResourceRequestParams, InputResponseRequestParams {}\n\n/**\n * Sent from the client to the server, to read a specific resource URI.\n *\n * @example Read resource request\n * {@includeCode ./examples/ReadResourceRequest/read-resource-request.json}\n *\n * @category `resources/read`\n */\nexport interface ReadResourceRequest extends JSONRPCRequest {\n method: \"resources/read\";\n params: ReadResourceRequestParams;\n}\n\n/**\n * The result returned by the server for a {@link ReadResourceRequest | resources/read} request.\n *\n * @example File resource contents\n * {@includeCode ./examples/ReadResourceResult/file-resource-contents.json}\n *\n * @category `resources/read`\n */\nexport interface ReadResourceResult extends CacheableResult {\n contents: (TextResourceContents | BlobResourceContents)[];\n}\n\n/**\n * A successful response from the server for a {@link ReadResourceRequest | resources/read} request.\n *\n * @example Read resource result response\n * {@includeCode ./examples/ReadResourceResultResponse/read-resource-result-response.json}\n *\n * @example Read resource result response with TTL\n * {@includeCode ./examples/ReadResourceResultResponse/read-resource-result-response-with-ttl.json}\n *\n * @category `resources/read`\n */\nexport interface ReadResourceResultResponse extends JSONRPCResultResponse {\n result: ReadResourceResult | InputRequiredResult;\n}\n\n/**\n * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.\n *\n * @example Resources list changed\n * {@includeCode ./examples/ResourceListChangedNotification/resources-list-changed.json}\n *\n * @category `notifications/resources/list_changed`\n */\nexport interface ResourceListChangedNotification extends JSONRPCNotification {\n method: \"notifications/resources/list_changed\";\n params?: NotificationParams;\n}\n\n/**\n * The set of notification types a client may opt in to on a\n * {@link SubscriptionsListenRequest | subscriptions/listen} request.\n *\n * Each notification type is **opt-in**; the server **MUST NOT** send\n * notification types the client has not explicitly requested here.\n *\n * @category `subscriptions/listen`\n */\nexport interface SubscriptionFilter {\n /**\n * If true, receive {@link ToolListChangedNotification | notifications/tools/list_changed}.\n */\n toolsListChanged?: boolean;\n /**\n * If true, receive {@link PromptListChangedNotification | notifications/prompts/list_changed}.\n */\n promptsListChanged?: boolean;\n /**\n * If true, receive {@link ResourceListChangedNotification | notifications/resources/list_changed}.\n */\n resourcesListChanged?: boolean;\n /**\n * Subscribe to {@link ResourceUpdatedNotification | notifications/resources/updated} for these resource URIs.\n * Replaces the former `resources/subscribe` RPC.\n */\n resourceSubscriptions?: string[];\n}\n\n/**\n * Parameters for a {@link SubscriptionsListenRequest | subscriptions/listen} request.\n *\n * @category `subscriptions/listen`\n */\nexport interface SubscriptionsListenRequestParams extends RequestParams {\n /**\n * The notifications the client opts in to on this stream. The server\n * **MUST NOT** send notification types the client has not explicitly\n * requested.\n */\n notifications: SubscriptionFilter;\n}\n\n/**\n * Sent from the client to open a long-lived channel for receiving notifications\n * outside the context of a specific request. Replaces the previous HTTP GET\n * endpoint and ensures consistent behavior between HTTP and STDIO.\n *\n * @example Listen for tools and resource list changes\n * {@includeCode ./examples/SubscriptionsListenRequest/listen-for-list-changes.json}\n *\n * @category `subscriptions/listen`\n */\nexport interface SubscriptionsListenRequest extends JSONRPCRequest {\n method: \"subscriptions/listen\";\n params: SubscriptionsListenRequestParams;\n}\n\n/**\n * Parameters for a {@link SubscriptionsAcknowledgedNotification | notifications/subscriptions/acknowledged} notification.\n *\n * @category `notifications/subscriptions/acknowledged`\n */\nexport interface SubscriptionsAcknowledgedNotificationParams extends NotificationParams {\n /**\n * The subset of requested notification types the server agreed to honor.\n * Only includes notification types the server actually supports; if the\n * client requested an unsupported type (e.g., `promptsListChanged` when\n * the server has no prompts), it is omitted from this set.\n */\n notifications: SubscriptionFilter;\n}\n\n/**\n * Sent by the server as the first message on a\n * {@link SubscriptionsListenRequest | subscriptions/listen} stream to acknowledge\n * that the subscription has been established and to report which notification\n * types it agreed to honor.\n *\n * @example Listen acknowledged\n * {@includeCode ./examples/SubscriptionsAcknowledgedNotification/listen-acknowledged.json}\n *\n * @category `notifications/subscriptions/acknowledged`\n */\nexport interface SubscriptionsAcknowledgedNotification extends JSONRPCNotification {\n method: \"notifications/subscriptions/acknowledged\";\n params: SubscriptionsAcknowledgedNotificationParams;\n}\n\n/**\n * Parameters for a `notifications/resources/updated` notification.\n *\n * @example File resource updated\n * {@includeCode ./examples/ResourceUpdatedNotificationParams/file-resource-updated.json}\n *\n * @category `notifications/resources/updated`\n */\nexport interface ResourceUpdatedNotificationParams extends NotificationParams {\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n *\n * @format uri\n */\n uri: string;\n}\n\n/**\n * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This is only sent for resources the client opted in to via the `resourceSubscriptions` field of a {@link SubscriptionsListenRequest | subscriptions/listen} request.\n *\n * @example File resource updated notification\n * {@includeCode ./examples/ResourceUpdatedNotification/file-resource-updated-notification.json}\n *\n * @category `notifications/resources/updated`\n */\nexport interface ResourceUpdatedNotification extends JSONRPCNotification {\n method: \"notifications/resources/updated\";\n params: ResourceUpdatedNotificationParams;\n}\n\n/**\n * A known resource that the server is capable of reading.\n *\n * @example File resource with annotations\n * {@includeCode ./examples/Resource/file-resource-with-annotations.json}\n *\n * @category `resources/list`\n */\nexport interface Resource extends BaseMetadata, Icons {\n /**\n * The URI of this resource.\n *\n * @format uri\n */\n uri: string;\n\n /**\n * A description of what this resource represents.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description?: string;\n\n /**\n * The MIME type of this resource, if known.\n */\n mimeType?: string;\n\n /**\n * Optional annotations for the client.\n */\n annotations?: Annotations;\n\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size?: number;\n\n _meta?: MetaObject;\n}\n\n/**\n * A template description for resources available on the server.\n *\n * @category `resources/templates/list`\n */\nexport interface ResourceTemplate extends BaseMetadata, Icons {\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n *\n * @format uri-template\n */\n uriTemplate: string;\n\n /**\n * A description of what this template is for.\n *\n * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a \"hint\" to the model.\n */\n description?: string;\n\n /**\n * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.\n */\n mimeType?: string;\n\n /**\n * Optional annotations for the client.\n */\n annotations?: Annotations;\n\n _meta?: MetaObject;\n}\n\n/**\n * The contents of a specific resource or sub-resource.\n *\n * @internal\n */\nexport interface ResourceContents {\n /**\n * The URI of this resource.\n *\n * @format uri\n */\n uri: string;\n /**\n * The MIME type of this resource, if known.\n */\n mimeType?: string;\n\n _meta?: MetaObject;\n}\n\n/**\n * @example Text file contents\n * {@includeCode ./examples/TextResourceContents/text-file-contents.json}\n *\n * @category Content\n */\nexport interface TextResourceContents extends ResourceContents {\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: string;\n}\n\n/**\n * @example Image file contents\n * {@includeCode ./examples/BlobResourceContents/image-file-contents.json}\n *\n * @category Content\n */\nexport interface BlobResourceContents extends ResourceContents {\n /**\n * A base64-encoded string representing the binary data of the item.\n *\n * @format byte\n */\n blob: string;\n}\n\n/* Prompts */\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n *\n * @example List prompts request\n * {@includeCode ./examples/ListPromptsRequest/list-prompts-request.json}\n *\n * @category `prompts/list`\n */\nexport interface ListPromptsRequest extends PaginatedRequest {\n method: \"prompts/list\";\n}\n\n/**\n * The result returned by the server for a {@link ListPromptsRequest | prompts/list} request.\n *\n * @example Prompts list with cursor and TTL\n * {@includeCode ./examples/ListPromptsResult/prompts-list-with-cursor-and-ttl.json}\n *\n * @category `prompts/list`\n */\nexport interface ListPromptsResult extends PaginatedResult, CacheableResult {\n prompts: Prompt[];\n}\n\n/**\n * A successful response from the server for a {@link ListPromptsRequest | prompts/list} request.\n *\n * @example List prompts result response\n * {@includeCode ./examples/ListPromptsResultResponse/list-prompts-result-response.json}\n *\n * @category `prompts/list`\n */\nexport interface ListPromptsResultResponse extends JSONRPCResultResponse {\n result: ListPromptsResult;\n}\n\n/**\n * Parameters for a `prompts/get` request.\n *\n * @example Get code review prompt\n * {@includeCode ./examples/GetPromptRequestParams/get-code-review-prompt.json}\n *\n * @category `prompts/get`\n */\nexport interface GetPromptRequestParams extends InputResponseRequestParams {\n /**\n * The name of the prompt or prompt template.\n */\n name: string;\n /**\n * Arguments to use for templating the prompt.\n */\n arguments?: { [key: string]: string };\n}\n\n/**\n * Used by the client to get a prompt provided by the server.\n *\n * @example Get prompt request\n * {@includeCode ./examples/GetPromptRequest/get-prompt-request.json}\n *\n * @category `prompts/get`\n */\nexport interface GetPromptRequest extends JSONRPCRequest {\n method: \"prompts/get\";\n params: GetPromptRequestParams;\n}\n\n/**\n * The result returned by the server for a {@link GetPromptRequest | prompts/get} request.\n *\n * @example Code review prompt\n * {@includeCode ./examples/GetPromptResult/code-review-prompt.json}\n *\n * @category `prompts/get`\n */\nexport interface GetPromptResult extends Result {\n /**\n * An optional description for the prompt.\n */\n description?: string;\n messages: PromptMessage[];\n}\n\n/**\n * A successful response from the server for a {@link GetPromptRequest | prompts/get} request.\n *\n * @example Get prompt result response\n * {@includeCode ./examples/GetPromptResultResponse/get-prompt-result-response.json}\n *\n * @category `prompts/get`\n */\nexport interface GetPromptResultResponse extends JSONRPCResultResponse {\n result: GetPromptResult | InputRequiredResult;\n}\n\n/**\n * A prompt or prompt template that the server offers.\n *\n * @category `prompts/list`\n */\nexport interface Prompt extends BaseMetadata, Icons {\n /**\n * An optional description of what this prompt provides\n */\n description?: string;\n\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments?: PromptArgument[];\n\n _meta?: MetaObject;\n}\n\n/**\n * Describes an argument that a prompt can accept.\n *\n * @category `prompts/list`\n */\nexport interface PromptArgument extends BaseMetadata {\n /**\n * A human-readable description of the argument.\n */\n description?: string;\n /**\n * Whether this argument must be provided.\n */\n required?: boolean;\n}\n\n/**\n * The sender or recipient of messages and data in a conversation.\n *\n * @category Common Types\n */\nexport type Role = \"user\" | \"assistant\";\n\n/**\n * Describes a message returned as part of a prompt.\n *\n * This is similar to {@link SamplingMessage}, but also supports the embedding of\n * resources from the MCP server.\n *\n * @category `prompts/get`\n */\nexport interface PromptMessage {\n role: Role;\n content: ContentBlock;\n}\n\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of {@link ListResourcesRequest | resources/list} requests.\n *\n * @example File resource link\n * {@includeCode ./examples/ResourceLink/file-resource-link.json}\n *\n * @category Content\n */\nexport interface ResourceLink extends Resource {\n type: \"resource_link\";\n}\n\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n *\n * It is up to the client how best to render embedded resources for the benefit\n * of the LLM and/or the user.\n *\n * @example Embedded file resource with annotations\n * {@includeCode ./examples/EmbeddedResource/embedded-file-resource-with-annotations.json}\n *\n * @category Content\n */\nexport interface EmbeddedResource {\n type: \"resource\";\n resource: TextResourceContents | BlobResourceContents;\n\n /**\n * Optional annotations for the client.\n */\n annotations?: Annotations;\n\n _meta?: MetaObject;\n}\n/**\n * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.\n *\n * @example Prompts list changed\n * {@includeCode ./examples/PromptListChangedNotification/prompts-list-changed.json}\n *\n * @category `notifications/prompts/list_changed`\n */\nexport interface PromptListChangedNotification extends JSONRPCNotification {\n method: \"notifications/prompts/list_changed\";\n params?: NotificationParams;\n}\n\n/* Tools */\n/**\n * Sent from the client to request a list of tools the server has.\n *\n * @example List tools request\n * {@includeCode ./examples/ListToolsRequest/list-tools-request.json}\n *\n * @category `tools/list`\n */\nexport interface ListToolsRequest extends PaginatedRequest {\n method: \"tools/list\";\n}\n\n/**\n * The result returned by the server for a {@link ListToolsRequest | tools/list} request.\n *\n * @example Tools list with cursor and TTL\n * {@includeCode ./examples/ListToolsResult/tools-list-with-cursor-and-ttl.json}\n *\n * @category `tools/list`\n */\nexport interface ListToolsResult extends PaginatedResult, CacheableResult {\n tools: Tool[];\n}\n\n/**\n * A successful response from the server for a {@link ListToolsRequest | tools/list} request.\n *\n * @example List tools result response\n * {@includeCode ./examples/ListToolsResultResponse/list-tools-result-response.json}\n *\n * @category `tools/list`\n */\nexport interface ListToolsResultResponse extends JSONRPCResultResponse {\n result: ListToolsResult;\n}\n\n/**\n * The result returned by the server for a {@link CallToolRequest | tools/call} request.\n *\n * @example Result with unstructured text\n * {@includeCode ./examples/CallToolResult/result-with-unstructured-text.json}\n *\n * @example Result with structured content\n * {@includeCode ./examples/CallToolResult/result-with-structured-content.json}\n *\n * @example Invalid tool input error\n * {@includeCode ./examples/CallToolResult/invalid-tool-input-error.json}\n *\n * @category `tools/call`\n */\nexport interface CallToolResult extends Result {\n /**\n * A list of content objects that represent the unstructured result of the tool call.\n */\n content: ContentBlock[];\n\n /**\n * An optional JSON value that represents the structured result of the tool call.\n *\n * This can be any JSON value (object, array, string, number, boolean, or null)\n * that conforms to the tool's outputSchema if one is defined.\n */\n structuredContent?: unknown;\n\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError?: boolean;\n}\n\n/**\n * A successful response from the server for a {@link CallToolRequest | tools/call} request.\n *\n * @example Call tool result response\n * {@includeCode ./examples/CallToolResultResponse/call-tool-result-response.json}\n *\n * @category `tools/call`\n */\nexport interface CallToolResultResponse extends JSONRPCResultResponse {\n result: CallToolResult | InputRequiredResult;\n}\n\n/**\n * Parameters for a `tools/call` request.\n *\n * @example `get_weather` tool call params\n * {@includeCode ./examples/CallToolRequestParams/get-weather-tool-call-params.json}\n *\n * @example Tool call params with progress token\n * {@includeCode ./examples/CallToolRequestParams/tool-call-params-with-progress-token.json}\n *\n * @category `tools/call`\n */\nexport interface CallToolRequestParams extends InputResponseRequestParams {\n /**\n * The name of the tool.\n */\n name: string;\n /**\n * Arguments to use for the tool call.\n */\n arguments?: { [key: string]: unknown };\n}\n\n/**\n * Used by the client to invoke a tool provided by the server.\n *\n * @example Call tool request\n * {@includeCode ./examples/CallToolRequest/call-tool-request.json}\n *\n * @category `tools/call`\n */\nexport interface CallToolRequest extends JSONRPCRequest {\n method: \"tools/call\";\n params: CallToolRequestParams;\n}\n\n/**\n * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.\n *\n * @example Tools list changed\n * {@includeCode ./examples/ToolListChangedNotification/tools-list-changed.json}\n *\n * @category `notifications/tools/list_changed`\n */\nexport interface ToolListChangedNotification extends JSONRPCNotification {\n method: \"notifications/tools/list_changed\";\n params?: NotificationParams;\n}\n\n/**\n * Additional properties describing a {@link Tool} to clients.\n *\n * NOTE: all properties in `ToolAnnotations` are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on `ToolAnnotations`\n * received from untrusted servers.\n *\n * @category `tools/list`\n */\nexport interface ToolAnnotations {\n /**\n * A human-readable title for the tool.\n */\n title?: string;\n\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint?: boolean;\n\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint?: boolean;\n\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint?: boolean;\n\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint?: boolean;\n}\n\n/**\n * Definition for a tool the client can call.\n *\n * @example With default 2020-12 input schema\n * {@includeCode ./examples/Tool/with-default-2020-12-input-schema.json}\n *\n * @example With explicit draft-07 input schema\n * {@includeCode ./examples/Tool/with-explicit-draft-07-input-schema.json}\n *\n * @example With no parameters\n * {@includeCode ./examples/Tool/with-no-parameters.json}\n *\n * @example With output schema for structured content\n * {@includeCode ./examples/Tool/with-output-schema-for-structured-content.json}\n *\n * @category `tools/list`\n */\nexport interface Tool extends BaseMetadata, Icons {\n /**\n * A human-readable description of the tool.\n *\n * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.\n */\n description?: string;\n\n /**\n * A JSON Schema object defining the expected parameters for the tool.\n *\n * Tool arguments are always JSON objects, so `type: \"object\"` is required at the root.\n * Beyond that, any JSON Schema 2020-12 keyword may appear alongside `type` — including\n * composition keywords (`oneOf`, `anyOf`, `allOf`, `not`), conditional keywords\n * (`if`/`then`/`else`), reference keywords (`$ref`, `$defs`, `$anchor`), and any other\n * standard validation or annotation keywords.\n *\n * Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided.\n */\n inputSchema: { $schema?: string; type: \"object\"; [key: string]: unknown };\n\n /**\n * An optional JSON Schema object defining the structure of the tool's output returned in\n * the structuredContent field of a {@link CallToolResult}. This can be any valid JSON Schema 2020-12.\n *\n * Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided.\n */\n outputSchema?: { $schema?: string; [key: string]: unknown };\n\n /**\n * Optional additional tool information.\n *\n * Display name precedence order is: `title`, `annotations.title`, then `name`.\n */\n annotations?: ToolAnnotations;\n\n _meta?: MetaObject;\n}\n\n/* Logging */\n\n/**\n * Parameters for a `notifications/message` notification.\n *\n * @example Log database connection failed\n * {@includeCode ./examples/LoggingMessageNotificationParams/log-database-connection-failed.json}\n *\n * @category `notifications/message`\n */\nexport interface LoggingMessageNotificationParams extends NotificationParams {\n /**\n * The severity of this log message.\n */\n level: LoggingLevel;\n /**\n * An optional name of the logger issuing this message.\n */\n logger?: string;\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: unknown;\n}\n\n/**\n * JSONRPCNotification of a log message passed from server to client. The client opts in by setting `\"io.modelcontextprotocol/logLevel\"` in a request's `_meta`.\n *\n * @example Log database connection failed\n * {@includeCode ./examples/LoggingMessageNotification/log-database-connection-failed.json}\n *\n * @category `notifications/message`\n */\nexport interface LoggingMessageNotification extends JSONRPCNotification {\n method: \"notifications/message\";\n params: LoggingMessageNotificationParams;\n}\n\n/**\n * The severity of a log message.\n *\n * These map to syslog message severities, as specified in RFC-5424:\n * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1\n *\n * @category Common Types\n */\nexport type LoggingLevel =\n | \"debug\"\n | \"info\"\n | \"notice\"\n | \"warning\"\n | \"error\"\n | \"critical\"\n | \"alert\"\n | \"emergency\";\n\n/* Sampling */\n/**\n * Parameters for a `sampling/createMessage` request.\n *\n * @example Basic request\n * {@includeCode ./examples/CreateMessageRequestParams/basic-request.json}\n *\n * @example Request with tools\n * {@includeCode ./examples/CreateMessageRequestParams/request-with-tools.json}\n *\n * @example Follow-up request with tool results\n * {@includeCode ./examples/CreateMessageRequestParams/follow-up-with-tool-results.json}\n *\n * @category `sampling/createMessage`\n */\nexport interface CreateMessageRequestParams {\n messages: SamplingMessage[];\n /**\n * The server's preferences for which model to select. The client MAY ignore these preferences.\n */\n modelPreferences?: ModelPreferences;\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt?: string;\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is `\"none\"`. Values `\"thisServer\"` and `\"allServers\"` are soft-deprecated. Servers SHOULD only use these values if the client\n * declares {@link ClientCapabilities.sampling.context}. These values may be removed in future spec releases.\n */\n includeContext?: \"none\" | \"thisServer\" | \"allServers\";\n /**\n * @TJS-type number\n */\n temperature?: number;\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: number;\n stopSequences?: string[];\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata?: JSONObject;\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.\n */\n tools?: Tool[];\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice?: ToolChoice;\n}\n\n/**\n * Controls tool selection behavior for sampling requests.\n *\n * @category `sampling/createMessage`\n */\nexport interface ToolChoice {\n /**\n * Controls the tool use ability of the model:\n * - `\"auto\"`: Model decides whether to use tools (default)\n * - `\"required\"`: Model MUST use at least one tool before completing\n * - `\"none\"`: Model MUST NOT use any tools\n */\n mode?: \"auto\" | \"required\" | \"none\";\n}\n\n/**\n * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.\n *\n * @example Sampling request\n * {@includeCode ./examples/CreateMessageRequest/sampling-request.json}\n *\n * @category `sampling/createMessage`\n */\nexport interface CreateMessageRequest {\n method: \"sampling/createMessage\";\n params: CreateMessageRequestParams;\n}\n\n/**\n * The result returned by the client for a {@link CreateMessageRequest | sampling/createMessage} request.\n * The client should inform the user before returning the sampled message, to allow them\n * to inspect the response (human in the loop) and decide whether to allow the server to see it.\n *\n * @example Text response\n * {@includeCode ./examples/CreateMessageResult/text-response.json}\n *\n * @example Tool use response\n * {@includeCode ./examples/CreateMessageResult/tool-use-response.json}\n *\n * @example Final response after tool use\n * {@includeCode ./examples/CreateMessageResult/final-response.json}\n *\n * @category `sampling/createMessage`\n */\nexport interface CreateMessageResult extends SamplingMessage {\n /**\n * The name of the model that generated the message.\n */\n model: string;\n\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - `\"endTurn\"`: Natural end of the assistant's turn\n * - `\"stopSequence\"`: A stop sequence was encountered\n * - `\"maxTokens\"`: Maximum token limit was reached\n * - `\"toolUse\"`: The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason?: \"endTurn\" | \"stopSequence\" | \"maxTokens\" | \"toolUse\" | string;\n}\n\n/**\n * Describes a message issued to or received from an LLM API.\n *\n * @example Single content block\n * {@includeCode ./examples/SamplingMessage/single-content-block.json}\n *\n * @example Multiple content blocks\n * {@includeCode ./examples/SamplingMessage/multiple-content-blocks.json}\n *\n * @category `sampling/createMessage`\n */\nexport interface SamplingMessage {\n role: Role;\n content: SamplingMessageContentBlock | SamplingMessageContentBlock[];\n _meta?: MetaObject;\n}\n\n/**\n * @category `sampling/createMessage`\n */\nexport type SamplingMessageContentBlock =\n | TextContent\n | ImageContent\n | AudioContent\n | ToolUseContent\n | ToolResultContent;\n\n/**\n * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed\n *\n * @category Common Types\n */\nexport interface Annotations {\n /**\n * Describes who the intended audience of this object or data is.\n *\n * It can include multiple entries to indicate content useful for multiple audiences (e.g., `[\"user\", \"assistant\"]`).\n */\n audience?: Role[];\n\n /**\n * Describes how important this data is for operating the server.\n *\n * A value of 1 means \"most important,\" and indicates that the data is\n * effectively required, while 0 means \"least important,\" and indicates that\n * the data is entirely optional.\n *\n * @TJS-type number\n * @minimum 0\n * @maximum 1\n */\n priority?: number;\n\n /**\n * The moment the resource was last modified, as an ISO 8601 formatted string.\n *\n * Should be an ISO 8601 formatted string (e.g., \"2025-01-12T15:00:58Z\").\n *\n * Examples: last activity timestamp in an open file, timestamp when the resource\n * was attached, etc.\n */\n lastModified?: string;\n}\n\n/**\n * @category Content\n */\nexport type ContentBlock =\n | TextContent\n | ImageContent\n | AudioContent\n | ResourceLink\n | EmbeddedResource;\n\n/**\n * Text provided to or from an LLM.\n *\n * @example Text content\n * {@includeCode ./examples/TextContent/text-content.json}\n *\n * @category Content\n */\nexport interface TextContent {\n type: \"text\";\n\n /**\n * The text content of the message.\n */\n text: string;\n\n /**\n * Optional annotations for the client.\n */\n annotations?: Annotations;\n\n _meta?: MetaObject;\n}\n\n/**\n * An image provided to or from an LLM.\n *\n * @example `image/png` content with annotations\n * {@includeCode ./examples/ImageContent/image-png-content-with-annotations.json}\n *\n * @category Content\n */\nexport interface ImageContent {\n type: \"image\";\n\n /**\n * The base64-encoded image data.\n *\n * @format byte\n */\n data: string;\n\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: string;\n\n /**\n * Optional annotations for the client.\n */\n annotations?: Annotations;\n\n _meta?: MetaObject;\n}\n\n/**\n * Audio provided to or from an LLM.\n *\n * @example `audio/wav` content\n * {@includeCode ./examples/AudioContent/audio-wav-content.json}\n *\n * @category Content\n */\nexport interface AudioContent {\n type: \"audio\";\n\n /**\n * The base64-encoded audio data.\n *\n * @format byte\n */\n data: string;\n\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: string;\n\n /**\n * Optional annotations for the client.\n */\n annotations?: Annotations;\n\n _meta?: MetaObject;\n}\n\n/**\n * A request from the assistant to call a tool.\n *\n * @example `get_weather` tool use\n * {@includeCode ./examples/ToolUseContent/get-weather-tool-use.json}\n *\n * @category `sampling/createMessage`\n */\nexport interface ToolUseContent {\n type: \"tool_use\";\n\n /**\n * A unique identifier for this tool use.\n *\n * This ID is used to match tool results to their corresponding tool uses.\n */\n id: string;\n\n /**\n * The name of the tool to call.\n */\n name: string;\n\n /**\n * The arguments to pass to the tool, conforming to the tool's input schema.\n */\n input: { [key: string]: unknown };\n\n /**\n * Optional metadata about the tool use. Clients SHOULD preserve this field when\n * including tool uses in subsequent sampling requests to enable caching optimizations.\n */\n _meta?: MetaObject;\n}\n\n/**\n * The result of a tool use, provided by the user back to the assistant.\n *\n * @example `get_weather` tool result\n * {@includeCode ./examples/ToolResultContent/get-weather-tool-result.json}\n *\n * @category `sampling/createMessage`\n */\nexport interface ToolResultContent {\n type: \"tool_result\";\n\n /**\n * The ID of the tool use this result corresponds to.\n *\n * This MUST match the ID from a previous {@link ToolUseContent}.\n */\n toolUseId: string;\n\n /**\n * The unstructured result content of the tool use.\n *\n * This has the same format as {@link CallToolResult.content} and can include text, images,\n * audio, resource links, and embedded resources.\n */\n content: ContentBlock[];\n\n /**\n * An optional structured result value.\n *\n * This can be any JSON value (object, array, string, number, boolean, or null).\n * If the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema.\n */\n structuredContent?: unknown;\n\n /**\n * Whether the tool use resulted in an error.\n *\n * If true, the content typically describes the error that occurred.\n * Default: false\n */\n isError?: boolean;\n\n /**\n * Optional metadata about the tool result. Clients SHOULD preserve this field when\n * including tool results in subsequent sampling requests to enable caching optimizations.\n */\n _meta?: MetaObject;\n}\n\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n *\n * Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n * rarely straightforward. Different models excel in different areas—some are\n * faster but less capable, others are more capable but more expensive, and so\n * on. This interface allows servers to express their priorities across multiple\n * dimensions to help clients make an appropriate selection for their use case.\n *\n * These preferences are always advisory. The client MAY ignore them. It is also\n * up to the client to decide how to interpret these preferences and how to\n * balance them against other considerations.\n *\n * @example With hints and priorities\n * {@includeCode ./examples/ModelPreferences/with-hints-and-priorities.json}\n *\n * @category `sampling/createMessage`\n */\nexport interface ModelPreferences {\n /**\n * Optional hints to use for model selection.\n *\n * If multiple hints are specified, the client MUST evaluate them in order\n * (such that the first match is taken).\n *\n * The client SHOULD prioritize these hints over the numeric priorities, but\n * MAY still use the priorities to select from ambiguous matches.\n */\n hints?: ModelHint[];\n\n /**\n * How much to prioritize cost when selecting a model. A value of 0 means cost\n * is not important, while a value of 1 means cost is the most important\n * factor.\n *\n * @TJS-type number\n * @minimum 0\n * @maximum 1\n */\n costPriority?: number;\n\n /**\n * How much to prioritize sampling speed (latency) when selecting a model. A\n * value of 0 means speed is not important, while a value of 1 means speed is\n * the most important factor.\n *\n * @TJS-type number\n * @minimum 0\n * @maximum 1\n */\n speedPriority?: number;\n\n /**\n * How much to prioritize intelligence and capabilities when selecting a\n * model. A value of 0 means intelligence is not important, while a value of 1\n * means intelligence is the most important factor.\n *\n * @TJS-type number\n * @minimum 0\n * @maximum 1\n */\n intelligencePriority?: number;\n}\n\n/**\n * Hints to use for model selection.\n *\n * Keys not declared here are currently left unspecified by the spec and are up\n * to the client to interpret.\n *\n * @category `sampling/createMessage`\n */\nexport interface ModelHint {\n /**\n * A hint for a model name.\n *\n * The client SHOULD treat this as a substring of a model name; for example:\n * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n * - `claude` should match any Claude model\n *\n * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example:\n * - `gemini-1.5-flash` could match `claude-3-haiku-20240307`\n */\n name?: string;\n}\n\n/* Autocomplete */\n/**\n * Parameters for a `completion/complete` request.\n *\n * @category `completion/complete`\n *\n * @example Prompt argument completion\n * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion.json}\n *\n * @example Prompt argument completion with context\n * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion-with-context.json}\n */\nexport interface CompleteRequestParams extends RequestParams {\n ref: PromptReference | ResourceTemplateReference;\n /**\n * The argument's information\n */\n argument: {\n /**\n * The name of the argument\n */\n name: string;\n /**\n * The value of the argument to use for completion matching.\n */\n value: string;\n };\n\n /**\n * Additional, optional context for completions\n */\n context?: {\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments?: { [key: string]: string };\n };\n}\n\n/**\n * A request from the client to the server, to ask for completion options.\n *\n * @example Completion request\n * {@includeCode ./examples/CompleteRequest/completion-request.json}\n *\n * @category `completion/complete`\n */\nexport interface CompleteRequest extends JSONRPCRequest {\n method: \"completion/complete\";\n params: CompleteRequestParams;\n}\n\n/**\n * The result returned by the server for a {@link CompleteRequest | completion/complete} request.\n *\n * @category `completion/complete`\n *\n * @example Single completion value\n * {@includeCode ./examples/CompleteResult/single-completion-value.json}\n *\n * @example Multiple completion values with more available\n * {@includeCode ./examples/CompleteResult/multiple-completion-values-with-more-available.json}\n */\nexport interface CompleteResult extends Result {\n completion: {\n /**\n * An array of completion values. Must not exceed 100 items.\n *\n * @maxItems 100\n */\n values: string[];\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total?: number;\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore?: boolean;\n };\n}\n\n/**\n * A successful response from the server for a {@link CompleteRequest | completion/complete} request.\n *\n * @example Completion result response\n * {@includeCode ./examples/CompleteResultResponse/completion-result-response.json}\n *\n * @category `completion/complete`\n */\nexport interface CompleteResultResponse extends JSONRPCResultResponse {\n result: CompleteResult;\n}\n\n/**\n * A reference to a resource or resource template definition.\n *\n * @category `completion/complete`\n */\nexport interface ResourceTemplateReference {\n type: \"ref/resource\";\n /**\n * The URI or URI template of the resource.\n *\n * @format uri-template\n */\n uri: string;\n}\n\n/**\n * Identifies a prompt.\n *\n * @category `completion/complete`\n */\nexport interface PromptReference extends BaseMetadata {\n type: \"ref/prompt\";\n}\n\n/* Roots */\n/**\n * Sent from the server to request a list of root URIs from the client. Roots allow\n * servers to ask for specific directories or files to operate on. A common example\n * for roots is providing a set of repositories or directories a server should operate\n * on.\n *\n * This request is typically used when the server needs to understand the file system\n * structure or access specific locations that the client has permission to read from.\n *\n * @example List roots request\n * {@includeCode ./examples/ListRootsRequest/list-roots-request.json}\n *\n * @category `roots/list`\n */\nexport interface ListRootsRequest {\n method: \"roots/list\";\n params?: RequestParams;\n}\n\n/**\n * The result returned by the client for a {@link ListRootsRequest | roots/list} request.\n * This result contains an array of {@link Root} objects, each representing a root directory\n * or file that the server can operate on.\n *\n * @example Single root directory\n * {@includeCode ./examples/ListRootsResult/single-root-directory.json}\n *\n * @example Multiple root directories\n * {@includeCode ./examples/ListRootsResult/multiple-root-directories.json}\n *\n * @category `roots/list`\n */\nexport interface ListRootsResult {\n roots: Root[];\n}\n\n/**\n * Represents a root directory or file that the server can operate on.\n *\n * @example Project directory root\n * {@includeCode ./examples/Root/project-directory.json}\n *\n * @category `roots/list`\n */\nexport interface Root {\n /**\n * The URI identifying the root. This *must* start with `file://` for now.\n * This restriction may be relaxed in future versions of the protocol to allow\n * other URI schemes.\n *\n * @format uri\n */\n uri: string;\n /**\n * An optional name for the root. This can be used to provide a human-readable\n * identifier for the root, which may be useful for display purposes or for\n * referencing the root in other parts of the application.\n */\n name?: string;\n\n _meta?: MetaObject;\n}\n\n/**\n * The parameters for a request to elicit non-sensitive information from the user via a form in the client.\n *\n * @example Elicit single field\n * {@includeCode ./examples/ElicitRequestFormParams/elicit-single-field.json}\n *\n * @example Elicit multiple fields\n * {@includeCode ./examples/ElicitRequestFormParams/elicit-multiple-fields.json}\n *\n * @category `elicitation/create`\n */\nexport interface ElicitRequestFormParams {\n /**\n * The elicitation mode.\n */\n mode?: \"form\";\n\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: string;\n\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: {\n $schema?: string;\n type: \"object\";\n properties: {\n [key: string]: PrimitiveSchemaDefinition;\n };\n required?: string[];\n };\n}\n\n/**\n * The parameters for a request to elicit information from the user via a URL in the client.\n *\n * @example Elicit sensitive data\n * {@includeCode ./examples/ElicitRequestURLParams/elicit-sensitive-data.json}\n *\n * @category `elicitation/create`\n */\nexport interface ElicitRequestURLParams {\n /**\n * The elicitation mode.\n */\n mode: \"url\";\n\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: string;\n\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: string;\n\n /**\n * The URL that the user should navigate to.\n *\n * @format uri\n */\n url: string;\n}\n\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n *\n * @category `elicitation/create`\n */\nexport type ElicitRequestParams =\n | ElicitRequestFormParams\n | ElicitRequestURLParams;\n\n/**\n * A request from the server to elicit additional information from the user via the client.\n *\n * @example Elicitation request\n * {@includeCode ./examples/ElicitRequest/elicitation-request.json}\n *\n * @category `elicitation/create`\n */\nexport interface ElicitRequest {\n method: \"elicitation/create\";\n params: ElicitRequestParams;\n}\n\n/**\n * Restricted schema definitions that only allow primitive types\n * without nested objects or arrays.\n *\n * @category `elicitation/create`\n */\nexport type PrimitiveSchemaDefinition =\n | StringSchema\n | NumberSchema\n | BooleanSchema\n | EnumSchema;\n\n/**\n * @example Email input schema\n * {@includeCode ./examples/StringSchema/email-input-schema.json}\n *\n * @category `elicitation/create`\n */\nexport interface StringSchema {\n type: \"string\";\n title?: string;\n description?: string;\n minLength?: number;\n maxLength?: number;\n format?: \"email\" | \"uri\" | \"date\" | \"date-time\";\n default?: string;\n}\n\n/**\n * @example Number input schema\n * {@includeCode ./examples/NumberSchema/number-input-schema.json}\n *\n * @category `elicitation/create`\n */\nexport interface NumberSchema {\n type: \"number\" | \"integer\";\n title?: string;\n description?: string;\n minimum?: number;\n maximum?: number;\n default?: number;\n}\n\n/**\n * @example Boolean input schema\n * {@includeCode ./examples/BooleanSchema/boolean-input-schema.json}\n *\n * @category `elicitation/create`\n */\nexport interface BooleanSchema {\n type: \"boolean\";\n title?: string;\n description?: string;\n default?: boolean;\n}\n\n/**\n * Schema for single-selection enumeration without display titles for options.\n *\n * @example Color select schema\n * {@includeCode ./examples/UntitledSingleSelectEnumSchema/color-select-schema.json}\n *\n * @category `elicitation/create`\n */\nexport interface UntitledSingleSelectEnumSchema {\n type: \"string\";\n /**\n * Optional title for the enum field.\n */\n title?: string;\n /**\n * Optional description for the enum field.\n */\n description?: string;\n /**\n * Array of enum values to choose from.\n */\n enum: string[];\n /**\n * Optional default value.\n */\n default?: string;\n}\n\n/**\n * Schema for single-selection enumeration with display titles for each option.\n *\n * @example Titled color select schema\n * {@includeCode ./examples/TitledSingleSelectEnumSchema/titled-color-select-schema.json}\n *\n * @category `elicitation/create`\n */\nexport interface TitledSingleSelectEnumSchema {\n type: \"string\";\n /**\n * Optional title for the enum field.\n */\n title?: string;\n /**\n * Optional description for the enum field.\n */\n description?: string;\n /**\n * Array of enum options with values and display labels.\n */\n oneOf: Array<{\n /**\n * The enum value.\n */\n const: string;\n /**\n * Display label for this option.\n */\n title: string;\n }>;\n /**\n * Optional default value.\n */\n default?: string;\n}\n\n/**\n * @category `elicitation/create`\n */\n// Combined single selection enumeration\nexport type SingleSelectEnumSchema =\n | UntitledSingleSelectEnumSchema\n | TitledSingleSelectEnumSchema;\n\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n *\n * @example Color multi-select schema\n * {@includeCode ./examples/UntitledMultiSelectEnumSchema/color-multi-select-schema.json}\n *\n * @category `elicitation/create`\n */\nexport interface UntitledMultiSelectEnumSchema {\n type: \"array\";\n /**\n * Optional title for the enum field.\n */\n title?: string;\n /**\n * Optional description for the enum field.\n */\n description?: string;\n /**\n * Minimum number of items to select.\n */\n minItems?: number;\n /**\n * Maximum number of items to select.\n */\n maxItems?: number;\n /**\n * Schema for the array items.\n */\n items: {\n type: \"string\";\n /**\n * Array of enum values to choose from.\n */\n enum: string[];\n };\n /**\n * Optional default value.\n */\n default?: string[];\n}\n\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n *\n * @example Titled color multi-select schema\n * {@includeCode ./examples/TitledMultiSelectEnumSchema/titled-color-multi-select-schema.json}\n *\n * @category `elicitation/create`\n */\nexport interface TitledMultiSelectEnumSchema {\n type: \"array\";\n /**\n * Optional title for the enum field.\n */\n title?: string;\n /**\n * Optional description for the enum field.\n */\n description?: string;\n /**\n * Minimum number of items to select.\n */\n minItems?: number;\n /**\n * Maximum number of items to select.\n */\n maxItems?: number;\n /**\n * Schema for array items with enum options and display labels.\n */\n items: {\n /**\n * Array of enum options with values and display labels.\n */\n anyOf: Array<{\n /**\n * The constant enum value.\n */\n const: string;\n /**\n * Display title for this option.\n */\n title: string;\n }>;\n };\n /**\n * Optional default value.\n */\n default?: string[];\n}\n\n/**\n * @category `elicitation/create`\n */\n// Combined multiple selection enumeration\nexport type MultiSelectEnumSchema =\n | UntitledMultiSelectEnumSchema\n | TitledMultiSelectEnumSchema;\n\n/**\n * Use {@link TitledSingleSelectEnumSchema} instead.\n * This interface will be removed in a future version.\n *\n * @category `elicitation/create`\n */\nexport interface LegacyTitledEnumSchema {\n type: \"string\";\n title?: string;\n description?: string;\n enum: string[];\n /**\n * (Legacy) Display names for enum values.\n * Non-standard according to JSON schema 2020-12.\n */\n enumNames?: string[];\n default?: string;\n}\n\n/**\n * @category `elicitation/create`\n */\n// Union type for all enum schemas\nexport type EnumSchema =\n | SingleSelectEnumSchema\n | MultiSelectEnumSchema\n | LegacyTitledEnumSchema;\n\n/**\n * The result returned by the client for an {@link ElicitRequest| elicitation/create} request.\n *\n * @example Input single field\n * {@includeCode ./examples/ElicitResult/input-single-field.json}\n *\n * @example Input multiple fields\n * {@includeCode ./examples/ElicitResult/input-multiple-fields.json}\n *\n * @example Accept URL mode (no content)\n * {@includeCode ./examples/ElicitResult/accept-url-mode-no-content.json}\n *\n * @category `elicitation/create`\n */\nexport interface ElicitResult {\n /**\n * The user action in response to the elicitation.\n * - `\"accept\"`: User submitted the form/confirmed the action\n * - `\"decline\"`: User explicitly declined the action\n * - `\"cancel\"`: User dismissed without making an explicit choice\n */\n action: \"accept\" | \"decline\" | \"cancel\";\n\n /**\n * The submitted form data, only present when action is `\"accept\"` and mode was `\"form\"`.\n * Contains values matching the requested schema.\n * Omitted for out-of-band mode responses.\n */\n content?: { [key: string]: string | number | boolean | string[] };\n}\n\n/**\n * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request.\n *\n * @example Elicitation complete\n * {@includeCode ./examples/ElicitationCompleteNotification/elicitation-complete.json}\n *\n * @category `notifications/elicitation/complete`\n */\nexport interface ElicitationCompleteNotification extends JSONRPCNotification {\n method: \"notifications/elicitation/complete\";\n params: {\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: string;\n };\n}\n\n/* Client messages */\n/** @internal */\nexport type ClientRequest =\n | DiscoverRequest\n | CompleteRequest\n | GetPromptRequest\n | ListPromptsRequest\n | ListResourcesRequest\n | ListResourceTemplatesRequest\n | ReadResourceRequest\n | SubscriptionsListenRequest\n | CallToolRequest\n | ListToolsRequest;\n\n/** @internal */\nexport type ClientNotification = CancelledNotification | ProgressNotification;\n\n/** @internal */\nexport type ClientResult = EmptyResult;\n\n/* Server messages */\n\n/** @internal */\nexport type ServerNotification =\n | CancelledNotification\n | ProgressNotification\n | LoggingMessageNotification\n | ResourceUpdatedNotification\n | ResourceListChangedNotification\n | ToolListChangedNotification\n | PromptListChangedNotification\n | ElicitationCompleteNotification\n | SubscriptionsAcknowledgedNotification;\n\n/** @internal */\nexport type ServerResult =\n | EmptyResult\n | DiscoverResult\n | CompleteResult\n | GetPromptResult\n | ListPromptsResult\n | ListResourceTemplatesResult\n | ListResourcesResult\n | ReadResourceResult\n | CallToolResult\n | ListToolsResult\n | InputRequiredResult;\n","import type { JsonObject, McpPrimitive, ToolDefinition, ToolResult } from \"../types.js\";\n\nconst primitiveSchema = {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n name: { type: \"string\" },\n primitiveName: { type: \"string\" },\n filePath: { type: [\"string\", \"null\"] },\n importPath: { type: [\"string\", \"null\"] },\n packageName: { type: [\"string\", \"null\"] },\n description: { type: \"string\" },\n usageGuidance: { type: \"string\" },\n props: { type: \"object\" },\n examples: { type: \"array\" },\n sourceRepoFullName: { type: [\"string\", \"null\"] },\n },\n required: [\"id\", \"name\", \"primitiveName\", \"filePath\", \"importPath\"],\n additionalProperties: true,\n} as const;\n\nexport const primitiveTools: ToolDefinition[] = [\n {\n name: \"design_system/list_primitives\",\n title: \"List Primitives\",\n description:\n \"List the design-system primitives curated in Fragments Cloud. Returns only reviewed primitives with their source file paths.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n maxProperties: 0,\n },\n outputSchema: {\n type: \"object\",\n properties: {\n primitiveCount: { type: \"integer\" },\n primitives: { type: \"array\", items: primitiveSchema },\n },\n required: [\"primitiveCount\", \"primitives\"],\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n },\n async call(_args, context) {\n const primitives = await context.provider.listPrimitives();\n return primitiveResult(primitives);\n },\n },\n];\n\nfunction primitiveResult(primitives: McpPrimitive[]): ToolResult {\n return {\n content: [\n {\n type: \"text\",\n text:\n primitives.length === 0\n ? \"No primitives have been selected in Fragments Cloud yet.\"\n : `Found ${primitives.length} primitives.`,\n },\n ],\n structuredContent: {\n primitiveCount: primitives.length,\n primitives: primitives.map(normalizePrimitive),\n },\n };\n}\n\nfunction normalizePrimitive(primitive: McpPrimitive): JsonObject {\n return {\n id: primitive.id,\n name: primitive.name,\n primitiveName: primitive.primitiveName ?? primitive.name,\n filePath: primitive.filePath ?? null,\n importPath: primitive.importPath ?? null,\n packageName: primitive.packageName ?? null,\n description: primitive.description ?? \"\",\n usageGuidance: primitive.usageGuidance ?? \"\",\n props: primitive.props ?? {},\n examples: primitive.examples ?? [],\n sourceRepoFullName: primitive.sourceRepoFullName ?? null,\n };\n}\n","import type { ConformInput, ConformResult, ToolDefinition, ToolResult } from \"../types.js\";\n\nconst locationSchema = {\n type: \"object\",\n properties: {\n line: { type: \"integer\" },\n column: { type: \"integer\" },\n endLine: { type: \"integer\" },\n endColumn: { type: \"integer\" },\n },\n additionalProperties: false,\n} as const;\n\nconst changeSchema = {\n type: \"object\",\n properties: {\n kind: {\n type: \"string\",\n enum: [\"swap-component\", \"rewrite-import\", \"rename-prop\", \"replace-token\", \"add-fallback\"],\n },\n ruleId: { type: \"string\" },\n code: { type: \"string\" },\n severity: { type: \"string\", enum: [\"error\", \"warning\", \"info\"] },\n message: { type: \"string\" },\n before: { type: \"string\" },\n after: { type: \"string\" },\n canonical: { type: \"string\" },\n confidence: { type: \"string\", enum: [\"high\", \"medium\", \"low\"] },\n location: locationSchema,\n },\n required: [\"kind\", \"severity\", \"message\", \"confidence\"],\n additionalProperties: false,\n} as const;\n\nconst suggestionSchema = {\n type: \"object\",\n properties: {\n kind: {\n type: \"string\",\n enum: [\"map-prop-value\", \"choose-among-alternates\", \"review-low-confidence\"],\n },\n message: { type: \"string\" },\n canonical: { type: \"string\" },\n hint: { type: \"string\" },\n confidence: { type: \"string\", enum: [\"high\", \"medium\", \"low\"] },\n location: locationSchema,\n },\n required: [\"kind\", \"message\", \"confidence\"],\n additionalProperties: false,\n} as const;\n\nconst unresolvedSchema = {\n type: \"object\",\n properties: {\n element: { type: \"string\" },\n canonical: { type: \"string\" },\n reason: { type: \"string\" },\n location: locationSchema,\n },\n required: [\"reason\"],\n additionalProperties: false,\n} as const;\n\nexport const conformTools: ToolDefinition[] = [\n {\n name: \"design_system/conform\",\n title: \"Conform to Design System\",\n description:\n \"Rewrite a snippet of UI code so it matches THIS project's design system. \" +\n \"Swaps raw HTML elements and components from other libraries (Material UI, \" +\n \"shadcn/ui, Chakra, or custom) to the project's own components and import \" +\n \"paths, replaces hardcoded colors/spacing/radii with the project's design \" +\n \"tokens, and flags accessibility gaps. Call this whenever the user says \" +\n \"'fix this', 'make this match our design system', 'use our components here', \" +\n \"right after pasting markup from elsewhere, or before committing UI you wrote. \" +\n \"Input is the code itself — no repo access needed. Returns a conformed version \" +\n \"plus a list of changes with rationale; ambiguous cross-library prop changes \" +\n \"come back as suggestions for you to apply.\",\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"The UI code to conform (JSX/TSX, HTML, or a CSS/SCSS block).\",\n },\n filename: {\n type: \"string\",\n description:\n \"Filename or extension hint for parser selection (e.g. 'Form.tsx', 'styles.scss'). Defaults to TSX.\",\n },\n apply: {\n type: \"string\",\n enum: [\"deterministic\", \"none\"],\n description:\n \"deterministic (default): return code with safe edits applied. none: findings only.\",\n },\n },\n required: [\"code\"],\n additionalProperties: false,\n },\n outputSchema: {\n type: \"object\",\n properties: {\n conformed: { type: \"string\" },\n changed: { type: \"boolean\" },\n summary: { type: \"string\" },\n designSystem: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n importsAdded: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"importsAdded\"],\n additionalProperties: false,\n },\n changes: { type: \"array\", items: changeSchema },\n suggestions: { type: \"array\", items: suggestionSchema },\n unresolved: { type: \"array\", items: unresolvedSchema },\n },\n required: [\"conformed\", \"changed\", \"changes\", \"suggestions\"],\n additionalProperties: false,\n },\n annotations: {\n readOnlyHint: true,\n idempotentHint: true,\n // Output depends on the `code` argument, so it must not be served from a\n // tenant-wide cache the way argument-free tools (list_primitives) are.\n cacheScope: \"none\",\n ttlMs: 0,\n },\n async call(args, context) {\n const input: ConformInput = {\n code: typeof args.code === \"string\" ? args.code : \"\",\n filename: typeof args.filename === \"string\" ? args.filename : undefined,\n apply: args.apply === \"none\" ? \"none\" : \"deterministic\",\n };\n const result = await context.provider.conform(input);\n return conformResult(result);\n },\n },\n];\n\nfunction conformResult(result: ConformResult): ToolResult {\n const summary = result.summary || defaultSummary(result);\n return {\n content: [{ type: \"text\", text: summary }],\n structuredContent: {\n conformed: result.conformed,\n changed: result.changed,\n summary,\n ...(result.designSystem\n ? {\n designSystem: {\n ...(result.designSystem.name ? { name: result.designSystem.name } : {}),\n importsAdded: result.designSystem.importsAdded ?? [],\n },\n }\n : {}),\n changes: result.changes,\n suggestions: result.suggestions,\n unresolved: result.unresolved,\n },\n };\n}\n\nfunction defaultSummary(result: ConformResult): string {\n if (!result.changed && result.changes.length === 0) {\n return \"No conformance changes were applied.\";\n }\n return `Applied ${result.changes.length} change(s); ${result.suggestions.length} suggestion(s) left for review.`;\n}\n","const locationSchema = {\n type: \"object\",\n properties: {\n line: { type: \"integer\" },\n column: { type: \"integer\" },\n endLine: { type: \"integer\" },\n endColumn: { type: \"integer\" },\n },\n additionalProperties: false,\n} as const;\n\nconst residualSchema = {\n type: \"object\",\n properties: {\n reason: { type: \"string\" },\n message: { type: \"string\" },\n canonical: { type: \"string\" },\n element: { type: \"string\" },\n hint: { type: \"string\" },\n confidence: { type: \"string\" },\n location: locationSchema,\n },\n additionalProperties: true,\n} as const;\n\nexport const proveCompliantOutputSchema = {\n type: \"object\",\n properties: {\n provedCompliant: { type: \"boolean\" },\n conformed: { type: \"string\" },\n changed: { type: \"boolean\" },\n passes: { type: \"integer\" },\n maxPasses: { type: \"integer\" },\n initialIssueCount: { type: \"integer\" },\n finalIssueCount: { type: \"integer\" },\n corrections: { type: \"integer\" },\n summary: { type: \"string\" },\n taskId: { type: \"string\" },\n changes: { type: \"array\", items: { type: \"object\", additionalProperties: true } },\n suggestions: { type: \"array\", items: residualSchema },\n unresolved: { type: \"array\", items: residualSchema },\n passHistory: { type: \"array\", items: { type: \"object\", additionalProperties: true } },\n },\n required: [\n \"provedCompliant\",\n \"conformed\",\n \"changed\",\n \"passes\",\n \"maxPasses\",\n \"initialIssueCount\",\n \"finalIssueCount\",\n \"corrections\",\n \"summary\",\n \"changes\",\n \"suggestions\",\n \"unresolved\",\n \"passHistory\",\n ],\n additionalProperties: false,\n} as const;\n","import type {\n ConformChange,\n ConformInput,\n ConformResult,\n ConformSuggestion,\n ConformUnresolved,\n InputRequiredToolResult,\n JsonObject,\n SamplingInputResponse,\n TaskRecord,\n ToolCallContext,\n ToolDefinition,\n ToolResult,\n} from \"../types.js\";\nimport { proveCompliantOutputSchema } from \"./prove-compliant-schema.js\";\n\nconst TOOL_NAME = \"design_system/prove_compliant\";\nconst DEFAULT_MAX_PASSES = 4;\nconst MAX_PASSES = 8;\nconst DEFAULT_TTL_MS = 15 * 60 * 1000;\n\ninterface ProveState {\n tool: typeof TOOL_NAME;\n code: string;\n filename?: string;\n maxPasses: number;\n allowSampling: boolean;\n passHistory: ProvePass[];\n corrections: number;\n taskId?: string;\n samplingAttempts: number;\n requestKey?: string;\n}\n\ninterface ProvePass {\n pass: number;\n issues: number;\n deterministicChanges: number;\n suggestions: number;\n unresolved: number;\n changed: boolean;\n sampling?: {\n requested?: boolean;\n used?: boolean;\n model?: string;\n stopReason?: string;\n reason?: string;\n };\n}\n\ninterface Residual {\n suggestions: ConformSuggestion[];\n unresolved: ConformUnresolved[];\n}\n\ninterface SamplingConsumption {\n attempted: boolean;\n code?: string;\n model?: string;\n stopReason?: string;\n reason?: string;\n}\n\nexport const proveCompliantTools: ToolDefinition[] = [\n {\n name: TOOL_NAME,\n title: \"Prove Design-System Compliance\",\n description:\n \"Run a closed validate-fix-validate loop over generated UI code until \" +\n \"Fragments can prove it has zero design-system findings, or return the \" +\n \"remaining issues. Uses deterministic fixes first, then MCP Sampling \" +\n \"when the connected client supports it.\",\n inputSchema: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description: \"The UI code to prove compliant.\",\n },\n filename: {\n type: \"string\",\n description: \"Filename or extension hint. Defaults to TSX.\",\n },\n maxPasses: {\n type: \"integer\",\n minimum: 1,\n maximum: MAX_PASSES,\n description: \"Maximum validation/fix passes. Defaults to 4.\",\n },\n allowSampling: {\n type: \"boolean\",\n description: \"Allow MCP Sampling for residual issues. Defaults to true.\",\n },\n },\n required: [\"code\"],\n additionalProperties: false,\n },\n outputSchema: proveCompliantOutputSchema,\n annotations: {\n readOnlyHint: true,\n idempotentHint: false,\n cacheScope: \"none\",\n ttlMs: 0,\n },\n async call(args, context) {\n return proveCompliant(args, context);\n },\n },\n];\n\nasync function proveCompliant(\n args: JsonObject,\n context: ToolCallContext\n): Promise<ToolResult | InputRequiredToolResult> {\n const restored = decodeState(context.requestState);\n const input = restored ?? initialState(args);\n const task = await ensureTask(context, input);\n if (task) input.taskId = task.taskId;\n\n const sampled = consumeSamplingResponse(input, context.inputResponses);\n if (sampled) {\n input.samplingAttempts += 1;\n if (sampled.code) {\n input.code = sampled.code;\n }\n const last = input.passHistory[input.passHistory.length - 1];\n if (last) {\n last.sampling = {\n ...(last.sampling ?? {}),\n used: Boolean(sampled.code),\n model: sampled.model,\n stopReason: sampled.stopReason,\n reason: sampled.reason,\n };\n }\n }\n\n let current = input.code;\n let lastResult: ConformResult | null = null;\n\n while (input.passHistory.length < input.maxPasses) {\n const pass = input.passHistory.length + 1;\n await updateTask(context, input.taskId, {\n status: \"working\",\n progress: {\n current: pass,\n total: input.maxPasses,\n message: `Validating pass ${pass}`,\n },\n });\n\n const result = await context.provider.conform({\n code: current,\n filename: input.filename,\n apply: \"deterministic\",\n });\n lastResult = result;\n const issues = issueCount(result);\n input.passHistory.push({\n pass,\n issues,\n deterministicChanges: result.changes.length,\n suggestions: result.suggestions.length,\n unresolved: result.unresolved.length,\n changed: result.changed,\n });\n input.corrections += result.changes.length;\n\n if (issues === 0) {\n const final = completeResult({\n state: input,\n result,\n originalCode: args.code,\n provedCompliant: true,\n reason: `0 findings after ${pass} pass${pass === 1 ? \"\" : \"es\"}.`,\n });\n return finish(context, input.taskId, final);\n }\n\n if (result.changed && result.conformed !== current) {\n current = result.conformed;\n input.code = current;\n continue;\n }\n\n const residual = {\n suggestions: result.suggestions,\n unresolved: result.unresolved,\n };\n if (canUseSampling(input, context, residual)) {\n return requestSampling({ state: input, context, current, residual });\n }\n break;\n }\n\n const fallback = lastResult ?? emptyConformResult(current);\n const final = completeResult({\n state: input,\n result: fallback,\n originalCode: args.code,\n provedCompliant: false,\n reason: incompleteReason(input, context, fallback),\n });\n return finish(context, input.taskId, final);\n}\n\nfunction initialState(args: JsonObject): ProveState {\n return {\n tool: TOOL_NAME,\n code: typeof args.code === \"string\" ? args.code : \"\",\n filename: typeof args.filename === \"string\" ? args.filename : undefined,\n maxPasses:\n typeof args.maxPasses === \"number\"\n ? Math.min(MAX_PASSES, Math.max(1, Math.trunc(args.maxPasses)))\n : DEFAULT_MAX_PASSES,\n allowSampling: args.allowSampling !== false,\n passHistory: [],\n corrections: 0,\n samplingAttempts: 0,\n };\n}\n\nasync function ensureTask(context: ToolCallContext, state: ProveState) {\n try {\n if (state.taskId) return await context.tasks.get(state.taskId);\n return await context.tasks.create({\n title: \"Prove UI compliance\",\n ttlMs: DEFAULT_TTL_MS,\n pollIntervalMs: 500,\n });\n } catch {\n return null;\n }\n}\n\nasync function requestSampling(args: {\n state: ProveState;\n context: ToolCallContext;\n current: string;\n residual: Residual;\n}): Promise<InputRequiredToolResult> {\n const requestKey = `prove_compliant_sampling_${args.state.passHistory.length}`;\n args.state.requestKey = requestKey;\n const last = args.state.passHistory[args.state.passHistory.length - 1];\n if (last) last.sampling = { requested: true };\n\n await updateTask(args.context, args.state.taskId, {\n status: \"input_required\",\n progress: {\n current: args.state.passHistory.length,\n total: args.state.maxPasses,\n message: \"Waiting for MCP Sampling to repair residual issues\",\n },\n });\n\n return {\n resultType: \"input_required\",\n inputRequests: {\n [requestKey]: {\n method: \"sampling/createMessage\",\n params: {\n messages: [\n {\n role: \"user\",\n content: {\n type: \"text\",\n text: samplingPrompt(args.current, args.residual),\n },\n },\n ],\n systemPrompt:\n \"You repair UI code for Fragments design-system governance. \" +\n \"Return only JSON with a single string field named code.\",\n includeContext: \"none\",\n maxTokens: 4000,\n temperature: 0.1,\n modelPreferences: {\n costPriority: 0.2,\n speedPriority: 0.3,\n intelligencePriority: 0.8,\n },\n },\n },\n },\n requestState: encodeState(args.state),\n };\n}\n\nfunction canUseSampling(state: ProveState, context: ToolCallContext, residual: Residual) {\n if (!state.allowSampling) return false;\n if (state.samplingAttempts >= state.maxPasses - 1) return false;\n if (residual.suggestions.length === 0 && residual.unresolved.length === 0) return false;\n const sampling = context.clientCapabilities?.sampling;\n return Boolean(sampling && typeof sampling === \"object\");\n}\n\nfunction consumeSamplingResponse(\n state: ProveState,\n responses: Record<string, unknown> | undefined\n): SamplingConsumption | null {\n if (!state.requestKey || !responses) return null;\n const response = responses[state.requestKey] as SamplingInputResponse | undefined;\n if (!response) return null;\n const text = extractText(response.content);\n const code = extractSampledCode(text);\n state.requestKey = undefined;\n if (!code) {\n return {\n attempted: true,\n reason: \"sampling response did not include code\",\n model: typeof response.model === \"string\" ? response.model : undefined,\n stopReason: typeof response.stopReason === \"string\" ? response.stopReason : undefined,\n };\n }\n return {\n attempted: true,\n code,\n model: typeof response.model === \"string\" ? response.model : undefined,\n stopReason: typeof response.stopReason === \"string\" ? response.stopReason : undefined,\n };\n}\n\nfunction completeResult(args: {\n state: ProveState;\n result: ConformResult;\n originalCode: unknown;\n provedCompliant: boolean;\n reason: string;\n}): ToolResult {\n const initialIssueCount = args.state.passHistory[0]?.issues ?? 0;\n const finalIssueCount = issueCount(args.result);\n const changed =\n typeof args.originalCode === \"string\" && args.result.conformed !== args.originalCode;\n const summary = args.provedCompliant\n ? `Proved compliant: ${args.reason}`\n : `Could not prove compliance: ${args.reason}`;\n return {\n content: [{ type: \"text\", text: summary }],\n structuredContent: {\n provedCompliant: args.provedCompliant,\n conformed: args.result.conformed,\n changed,\n passes: args.state.passHistory.length,\n maxPasses: args.state.maxPasses,\n initialIssueCount,\n finalIssueCount,\n corrections: args.state.corrections,\n summary,\n taskId: args.state.taskId,\n changes: args.result.changes,\n suggestions: args.result.suggestions,\n unresolved: args.result.unresolved,\n passHistory: args.state.passHistory,\n },\n };\n}\n\nasync function finish(context: ToolCallContext, taskId: string | undefined, result: ToolResult) {\n await updateTask(context, taskId, {\n status: \"completed\",\n result,\n progress: { current: 1, total: 1, message: \"Proof loop completed\" },\n });\n return result;\n}\n\nasync function updateTask(\n context: ToolCallContext,\n taskId: string | undefined,\n patch: Partial<TaskRecord>\n) {\n if (!taskId) return null;\n try {\n return await context.tasks.update(taskId, patch);\n } catch {\n return null;\n }\n}\n\nfunction issueCount(result: ConformResult): number {\n return result.changes.length + result.suggestions.length + result.unresolved.length;\n}\n\nfunction incompleteReason(\n state: ProveState,\n context: ToolCallContext,\n result: ConformResult\n): string {\n if (state.passHistory.length >= state.maxPasses) {\n return `stopped after ${state.maxPasses} passes with ${issueCount(result)} finding(s).`;\n }\n if (!state.allowSampling) return \"sampling was disabled and residual issues remain.\";\n if (!context.clientCapabilities?.sampling) {\n return \"the MCP client did not declare sampling support and residual issues remain.\";\n }\n return `${issueCount(result)} residual finding(s) remain after deterministic and sampled fixes.`;\n}\n\nfunction samplingPrompt(code: string, residual: Residual): string {\n return [\n \"Repair this UI code so it satisfies the remaining Fragments findings.\",\n \"Preserve behavior, text, event handlers, and existing imports unless a finding requires a change.\",\n 'Return JSON only: {\"code\":\"...full revised code...\"}.',\n \"\",\n \"Remaining findings:\",\n JSON.stringify(residual, null, 2),\n \"\",\n \"Current code:\",\n \"```tsx\",\n code,\n \"```\",\n ].join(\"\\n\");\n}\n\nfunction extractText(content: unknown): string {\n if (!content) return \"\";\n if (Array.isArray(content)) return content.map(extractText).join(\"\\n\");\n if (typeof content === \"object\") {\n const record = content as Record<string, unknown>;\n return typeof record.text === \"string\" ? record.text : \"\";\n }\n return typeof content === \"string\" ? content : \"\";\n}\n\nfunction extractSampledCode(text: string): string | null {\n const trimmed = text.trim();\n if (!trimmed) return null;\n try {\n const parsed = JSON.parse(trimmed) as { code?: unknown };\n if (typeof parsed.code === \"string\" && parsed.code.trim()) return parsed.code;\n } catch {\n // Continue to fenced/plain text extraction.\n }\n const fence = /```(?:[A-Za-z0-9_-]+)?\\n([\\s\\S]*?)```/.exec(trimmed);\n if (fence?.[1]?.trim()) return fence[1].trim();\n return trimmed;\n}\n\nfunction encodeState(state: ProveState): string {\n return JSON.stringify(state);\n}\n\nfunction decodeState(value: string | undefined): ProveState | null {\n if (!value) return null;\n try {\n const parsed = JSON.parse(value) as ProveState;\n return parsed?.tool === TOOL_NAME ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction emptyConformResult(code: string): ConformResult {\n return {\n conformed: code,\n changed: false,\n summary: \"No conform result was produced.\",\n changes: [],\n suggestions: [],\n unresolved: [],\n };\n}\n","import type { ToolDefinition } from \"../types.js\";\nimport { primitiveTools } from \"./primitives.js\";\nimport { conformTools } from \"./conform.js\";\nimport { proveCompliantTools } from \"./prove-compliant.js\";\n\nconst MAX_SCHEMA_DEPTH = 16;\n\nexport const MCP_TOOLS: ToolDefinition[] = [\n ...primitiveTools,\n ...conformTools,\n ...proveCompliantTools,\n];\n\nexport function getTool(name: string) {\n return MCP_TOOLS.find((tool) => tool.name === name) ?? null;\n}\n\nexport function listToolDescriptors() {\n return MCP_TOOLS.map(({ call: _call, ...tool }) => ({\n ...tool,\n inputSchema: validateToolSchema(tool.name, tool.inputSchema),\n ...(tool.outputSchema\n ? { outputSchema: validateToolSchema(tool.name, tool.outputSchema) }\n : {}),\n annotations: {\n cacheScope: \"tenant\",\n ttlMs: 60_000,\n ...(tool.annotations ?? {}),\n },\n }));\n}\n\nfunction validateToolSchema(toolName: string, schema: unknown) {\n assertSchemaNode(toolName, schema, 0);\n return schema;\n}\n\nfunction assertSchemaNode(toolName: string, value: unknown, depth: number) {\n if (depth > MAX_SCHEMA_DEPTH) {\n throw new Error(`Tool ${toolName} schema exceeds maximum depth`);\n }\n if (!value || typeof value !== \"object\") return;\n\n if (Array.isArray(value)) {\n for (const item of value) assertSchemaNode(toolName, item, depth + 1);\n return;\n }\n\n const record = value as Record<string, unknown>;\n const ref = record.$ref;\n if (typeof ref === \"string\" && !ref.startsWith(\"#/\")) {\n throw new Error(`Tool ${toolName} schema contains external $ref`);\n }\n\n for (const child of Object.values(record)) {\n assertSchemaNode(toolName, child, depth + 1);\n }\n}\n","import { MCP_APP_RESOURCES, getResource, listResources } from \"../apps/resources.js\";\nimport { MemoryTaskStore } from \"../tasks/store.js\";\nimport type {\n DataProvider,\n JsonObject,\n JsonRpcFailure,\n JsonRpcRequest,\n JsonRpcResponse,\n JsonRpcSuccess,\n TaskStore,\n ToolCallContext,\n} from \"../types.js\";\nimport { LATEST_PROTOCOL_VERSION } from \"../spec/index.js\";\nimport { getTool, listToolDescriptors } from \"../tools/registry.js\";\n\nexport interface FragmentsMcpServerOptions {\n provider: DataProvider;\n tasks?: TaskStore;\n}\n\nexport class McpProtocolError extends Error {\n readonly code: number;\n readonly data?: unknown;\n\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.code = code;\n this.data = data;\n }\n}\n\nexport class FragmentsMcpServer {\n private readonly provider: DataProvider;\n private readonly tasks: TaskStore;\n\n constructor(options: FragmentsMcpServerOptions) {\n this.provider = options.provider;\n this.tasks = options.tasks ?? new MemoryTaskStore();\n }\n\n async handleJsonRpc(request: JsonRpcRequest): Promise<JsonRpcResponse> {\n try {\n const result = await this.dispatch(request);\n return success(request.id ?? null, result);\n } catch (error) {\n return failure(request.id ?? null, toProtocolError(error));\n }\n }\n\n private async dispatch(request: JsonRpcRequest): Promise<unknown> {\n const params = request.params ?? {};\n switch (request.method) {\n case \"server/discover\":\n return this.discover();\n case \"tools/list\":\n return { tools: listToolDescriptors() };\n case \"tools/call\":\n return this.callTool(params);\n case \"resources/list\":\n return { resources: listResources() };\n case \"resources/read\":\n return this.readResource(params);\n case \"tasks/get\":\n return this.getTask(params);\n case \"tasks/update\":\n return this.updateTask(params);\n case \"tasks/cancel\":\n return this.cancelTask(params);\n default:\n throw new McpProtocolError(-32601, `Unknown MCP method ${request.method}`);\n }\n }\n\n private discover() {\n return {\n protocolVersion: LATEST_PROTOCOL_VERSION,\n serverInfo: {\n name: \"@fragments-sdk/mcp\",\n version: \"0.11.0-rc\",\n },\n capabilities: {\n tools: { listChanged: false },\n },\n };\n }\n\n private async callTool(params: JsonObject) {\n const name = requireString(params.name, \"name\");\n const tool = getTool(name);\n if (!tool) {\n throw new McpProtocolError(-32602, `Unknown tool ${name}`);\n }\n\n const context: ToolCallContext = {\n provider: this.provider,\n tasks: this.tasks,\n requestMeta: readMeta(params),\n clientCapabilities: readClientCapabilities(params),\n inputResponses: readInputResponses(params),\n requestState: readRequestState(params),\n };\n const args = readArgs(params);\n validateArgs(tool.name, tool.inputSchema, args);\n return tool.call(args, context);\n }\n\n private async readResource(params: JsonObject) {\n const uri = requireString(params.uri, \"uri\");\n const resource = getResource(uri);\n if (!resource) {\n throw new McpProtocolError(-32602, `Unknown resource ${uri}`);\n }\n\n return resource.read({\n provider: this.provider,\n tasks: this.tasks,\n requestMeta: readMeta(params),\n });\n }\n\n private async getTask(params: JsonObject) {\n const taskId = requireString(params.taskId, \"taskId\");\n const task = await this.tasks.get(taskId);\n if (!task) {\n throw new McpProtocolError(-32602, `Unknown task ${taskId}`);\n }\n return { task };\n }\n\n private async updateTask(params: JsonObject) {\n const taskId = requireString(params.taskId, \"taskId\");\n const task = await this.tasks.update(taskId, {});\n if (!task) {\n throw new McpProtocolError(-32602, `Unknown task ${taskId}`);\n }\n return { task };\n }\n\n private async cancelTask(params: JsonObject) {\n const taskId = requireString(params.taskId, \"taskId\");\n const task = await this.tasks.cancel(taskId);\n if (!task) {\n throw new McpProtocolError(-32602, `Unknown task ${taskId}`);\n }\n return { task };\n }\n}\n\nexport async function handleMcpJsonRpc(\n request: JsonRpcRequest,\n options: FragmentsMcpServerOptions\n): Promise<JsonRpcResponse> {\n return new FragmentsMcpServer(options).handleJsonRpc(request);\n}\n\nexport async function handleMcpHttpRequest(\n request: Request,\n options: FragmentsMcpServerOptions\n): Promise<Response> {\n let body: JsonRpcRequest;\n try {\n body = (await request.json()) as JsonRpcRequest;\n } catch {\n return Response.json(failure(null, new McpProtocolError(-32700, \"Invalid JSON\")), {\n status: 400,\n });\n }\n\n const response = await handleMcpJsonRpc(body, options);\n return Response.json(response, {\n status: \"error\" in response ? 400 : 200,\n headers: {\n \"Cache-Control\": \"no-store\",\n \"Mcp-Protocol-Version\": LATEST_PROTOCOL_VERSION,\n },\n });\n}\n\nfunction success(id: string | number | null, result: unknown): JsonRpcSuccess {\n return { jsonrpc: \"2.0\", id, result };\n}\n\nfunction failure(id: string | number | null, error: McpProtocolError): JsonRpcFailure {\n return {\n jsonrpc: \"2.0\",\n id,\n error: {\n code: error.code,\n message: error.message,\n data: error.data,\n },\n };\n}\n\nfunction toProtocolError(error: unknown) {\n if (error instanceof McpProtocolError) return error;\n return new McpProtocolError(\n -32603,\n error instanceof Error ? error.message : \"Internal MCP error\"\n );\n}\n\nfunction requireString(value: unknown, key: string) {\n if (typeof value === \"string\" && value.trim()) return value.trim();\n throw new McpProtocolError(-32602, `Missing ${key}`);\n}\n\nfunction readArgs(params: JsonObject): JsonObject {\n const args = params.arguments ?? {};\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return {};\n return args as JsonObject;\n}\n\nfunction readMeta(params: JsonObject): JsonObject | undefined {\n const meta = params._meta;\n if (!meta || typeof meta !== \"object\" || Array.isArray(meta)) return undefined;\n return meta as JsonObject;\n}\n\nfunction readClientCapabilities(params: JsonObject): JsonObject | undefined {\n const meta = readMeta(params);\n const capabilities = meta?.[\"io.modelcontextprotocol/clientCapabilities\"];\n if (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n return undefined;\n }\n return capabilities as JsonObject;\n}\n\nfunction readInputResponses(params: JsonObject): Record<string, unknown> | undefined {\n const responses = params.inputResponses;\n if (!responses || typeof responses !== \"object\" || Array.isArray(responses)) {\n return undefined;\n }\n return responses as Record<string, unknown>;\n}\n\nfunction readRequestState(params: JsonObject): string | undefined {\n return typeof params.requestState === \"string\" ? params.requestState : undefined;\n}\n\nfunction validateArgs(toolName: string, schema: JsonObject, args: JsonObject) {\n if (schema.type !== \"object\") return;\n const properties = readProperties(schema.properties);\n const required = Array.isArray(schema.required)\n ? schema.required.filter((item): item is string => typeof item === \"string\")\n : [];\n const argCount = Object.keys(args).filter(\n (key) => args[key] !== undefined && args[key] !== null\n ).length;\n if (typeof schema.minProperties === \"number\" && argCount < schema.minProperties) {\n throw new McpProtocolError(\n -32602,\n `Invalid arguments for ${toolName}: expected at least ${schema.minProperties} argument(s)`\n );\n }\n if (typeof schema.maxProperties === \"number\" && argCount > schema.maxProperties) {\n throw new McpProtocolError(\n -32602,\n `Invalid arguments for ${toolName}: expected at most ${schema.maxProperties} argument(s)`\n );\n }\n\n for (const key of required) {\n if (!(key in args) || args[key] === undefined || args[key] === null) {\n throw new McpProtocolError(-32602, `Invalid arguments for ${toolName}: missing ${key}`);\n }\n if (properties[key]?.type === \"string\" && typeof args[key] === \"string\" && !args[key].trim()) {\n throw new McpProtocolError(-32602, `Invalid arguments for ${toolName}: missing ${key}`);\n }\n }\n\n if (schema.additionalProperties === false) {\n for (const key of Object.keys(args)) {\n if (!(key in properties)) {\n throw new McpProtocolError(-32602, `Invalid arguments for ${toolName}: unknown ${key}`);\n }\n }\n }\n\n for (const [key, value] of Object.entries(args)) {\n const property = properties[key];\n if (!property || value === undefined || value === null) continue;\n validateValue(toolName, key, property, value);\n }\n}\n\nfunction readProperties(value: unknown): Record<string, JsonObject> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const properties: Record<string, JsonObject> = {};\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n if (child && typeof child === \"object\" && !Array.isArray(child)) {\n properties[key] = child as JsonObject;\n }\n }\n return properties;\n}\n\nfunction validateValue(toolName: string, key: string, schema: JsonObject, value: unknown) {\n if (Array.isArray(schema.enum) && !schema.enum.includes(value)) {\n throw new McpProtocolError(\n -32602,\n `Invalid arguments for ${toolName}: ${key} must be one of ${schema.enum.join(\", \")}`\n );\n }\n\n const type = schema.type;\n if (typeof type !== \"string\") return;\n\n const valid =\n type === \"integer\"\n ? typeof value === \"number\" && Number.isInteger(value)\n : type === \"number\"\n ? typeof value === \"number\" && Number.isFinite(value)\n : type === \"string\"\n ? typeof value === \"string\"\n : type === \"boolean\"\n ? typeof value === \"boolean\"\n : type === \"object\"\n ? !!value && typeof value === \"object\" && !Array.isArray(value)\n : true;\n\n if (!valid) {\n throw new McpProtocolError(-32602, `Invalid arguments for ${toolName}: ${key} must be ${type}`);\n }\n\n if (typeof value === \"number\" && typeof schema.minimum === \"number\" && value < schema.minimum) {\n throw new McpProtocolError(\n -32602,\n `Invalid arguments for ${toolName}: ${key} must be >= ${schema.minimum}`\n );\n }\n\n if (typeof value === \"number\" && typeof schema.maximum === \"number\" && value > schema.maximum) {\n throw new McpProtocolError(\n -32602,\n `Invalid arguments for ${toolName}: ${key} must be <= ${schema.maximum}`\n );\n }\n}\n\nexport { MCP_APP_RESOURCES };\n","import type { ConformResult, DataProvider, McpPrimitive } from \"../types.js\";\n\nexport const fixturePrimitives: McpPrimitive[] = [\n {\n id: \"button\",\n name: \"Button\",\n primitiveName: \"Button\",\n category: \"Actions\",\n status: \"ready\",\n description: \"Primary action trigger.\",\n usageGuidance: \"Use for explicit user actions.\",\n importPath: \"@fixture/ui/button\",\n packageName: \"@fixture/ui\",\n filePath: \"src/components/Button.tsx\",\n sourceRepoFullName: \"fixture/ui\",\n props: {\n variant: {\n type: '\"primary\" | \"secondary\"',\n required: false,\n description: \"Visual emphasis.\",\n },\n },\n },\n];\n\nexport const fixtureConformResult: ConformResult = {\n conformed:\n 'import { Button } from \"@fixture/ui\";\\n\\n<Button variant=\"primary\" style={{ padding: \"var(--space-4)\" }}>Send</Button>',\n changed: true,\n summary:\n \"Swapped <button> to Button (@fixture/ui), mapped #2563eb to --brand-600 and 16px to --space-4, flagged a missing accessible name.\",\n designSystem: {\n name: \"Fixture UI\",\n importsAdded: ['import { Button } from \"@fixture/ui\";'],\n },\n changes: [\n {\n kind: \"swap-component\",\n ruleId: \"components/preferred-component\",\n code: \"FUI0410\",\n severity: \"warning\",\n message: \"Replaced native <button> with the design-system Button.\",\n before: \"<button>\",\n after: '<Button variant=\"primary\">',\n canonical: \"Button\",\n confidence: \"high\",\n location: { line: 1, column: 1 },\n },\n {\n kind: \"replace-token\",\n ruleId: \"styles/no-raw-color\",\n code: \"FUI0601\",\n severity: \"error\",\n message: \"Replaced hardcoded color #2563eb with the matching design token.\",\n before: \"#2563eb\",\n after: \"var(--brand-600)\",\n confidence: \"high\",\n location: { line: 1, column: 16 },\n },\n {\n kind: \"replace-token\",\n ruleId: \"styles/no-raw-spacing\",\n code: \"FUI0602\",\n severity: \"warning\",\n message: \"Replaced hardcoded 16px with the matching spacing token.\",\n before: \"16px\",\n after: \"var(--space-4)\",\n confidence: \"high\",\n location: { line: 1, column: 38 },\n },\n ],\n suggestions: [\n {\n kind: \"review-low-confidence\",\n confidence: \"medium\",\n message:\n 'Button has no accessible name beyond its text. Confirm \"Send\" is descriptive or add an aria-label.',\n canonical: \"Button\",\n location: { line: 1, column: 1 },\n },\n ],\n unresolved: [],\n};\n\nexport function createFixtureProvider(args?: {\n primitives?: McpPrimitive[];\n conform?: ConformResult;\n}): DataProvider {\n const primitives = args?.primitives ?? fixturePrimitives;\n const conformResult = args?.conform ?? fixtureConformResult;\n return {\n async listPrimitives() {\n return primitives;\n },\n async conform() {\n return conformResult;\n },\n };\n}\n"],"mappings":";AAEO,IAAM,oBAA0C,CAAC;AAEjD,SAAS,YAAY,MAAyC;AACnE,SAAO;AACT;AAEO,SAAS,gBAAgB;AAC9B,SAAO,CAAC;AACV;;;ACRA,IAAI,aAAa;AAEjB,SAAS,eAAe;AACtB,QAAM,KAAK,QAAQ,OAAO,UAAU,EAAE,SAAS,GAAG,GAAG,CAAC;AACtD,gBAAc;AACd,SAAO;AACT;AAEO,IAAM,kBAAN,MAA2C;AAAA,EAC/B,QAAQ,oBAAI,IAAwB;AAAA,EAErD,MAAM,OAAO,OASW;AACtB,UAAM,MAAM,KAAK,IAAI;AACrB,UAAM,SAAS,MAAM,UAAU,wBAAwB,MAAM,UAAU,IAAI;AAC3E,UAAM,OAAmB;AAAA,MACvB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,MACE,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,UAAU;AAAA,MACV,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,WAAW;AAAA,MACX,YAAY;AAAA,MACZ,UAAU,EAAE,MAAM,GAAG,QAAQ,EAAE;AAAA,IACjC;AAAA,IACA;AAAA,MACE,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,UAAU;AAAA,MACV,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,UAAU,EAAE,MAAM,GAAG,QAAQ,GAAG;AAAA,IAClC;AAAA,IACA;AAAA,MACE,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,UAAU;AAAA,MACV,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,YAAY;AAAA,MACZ,UAAU,EAAE,MAAM,GAAG,QAAQ,GAAG;AAAA,IAClC;AAAA,EACF;AAAA,EACA,aAAa;AAAA,IACX;AAAA,MACE,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,SACE;AAAA,MACF,WAAW;AAAA,MACX,UAAU,EAAE,MAAM,GAAG,QAAQ,EAAE;AAAA,IACjC;AAAA,EACF;AAAA,EACA,YAAY,CAAC;AACf;AAEO,SAAS,sBAAsB,MAGrB;AACf,QAAM,aAAa,MAAM,cAAc;AACvC,QAAMC,iBAAgB,MAAM,WAAW;AACvC,SAAO;AAAA,IACL,MAAM,iBAAiB;AACrB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,UAAU;AACd,aAAOA;AAAA,IACT;AAAA,EACF;AACF;","names":["locationSchema","final","conformResult"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fragments-sdk/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.1",
|
|
4
4
|
"license": "FSL-1.1-MIT",
|
|
5
|
-
"description": "
|
|
5
|
+
"description": "Hosted MCP toolkit for Fragments design-system intelligence",
|
|
6
6
|
"mcpName": "io.github.ConanMcN/fragments-mcp",
|
|
7
7
|
"author": "Conan McNicholl",
|
|
8
8
|
"homepage": "https://usefragments.com",
|
|
@@ -14,29 +14,13 @@
|
|
|
14
14
|
"bin": {
|
|
15
15
|
"fragments-mcp": "./dist/bin.js"
|
|
16
16
|
},
|
|
17
|
-
"main": "./dist/
|
|
18
|
-
"module": "./dist/
|
|
19
|
-
"types": "./dist/
|
|
17
|
+
"main": "./dist/index.js",
|
|
18
|
+
"module": "./dist/index.js",
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
20
|
"exports": {
|
|
21
21
|
".": {
|
|
22
|
-
"types": "./dist/server.d.ts",
|
|
23
|
-
"import": "./dist/server.js"
|
|
24
|
-
},
|
|
25
|
-
"./index": {
|
|
26
22
|
"types": "./dist/index.d.ts",
|
|
27
23
|
"import": "./dist/index.js"
|
|
28
|
-
},
|
|
29
|
-
"./registry": {
|
|
30
|
-
"types": "./dist/registry.d.ts",
|
|
31
|
-
"import": "./dist/registry.js"
|
|
32
|
-
},
|
|
33
|
-
"./adapters": {
|
|
34
|
-
"types": "./dist/adapters/index.d.ts",
|
|
35
|
-
"import": "./dist/adapters/index.js"
|
|
36
|
-
},
|
|
37
|
-
"./middleware": {
|
|
38
|
-
"types": "./dist/middleware.d.ts",
|
|
39
|
-
"import": "./dist/middleware.js"
|
|
40
24
|
}
|
|
41
25
|
},
|
|
42
26
|
"keywords": [
|
|
@@ -59,27 +43,19 @@
|
|
|
59
43
|
},
|
|
60
44
|
"dependencies": {
|
|
61
45
|
"@scarf/scarf": "^1.4.0",
|
|
62
|
-
"@
|
|
63
|
-
"@orama/orama": "^3.1.18",
|
|
64
|
-
"typescript": "^5.7.2",
|
|
65
|
-
"@fragments-sdk/classifier": "0.2.1",
|
|
66
|
-
"@fragments-sdk/core": "3.2.0",
|
|
67
|
-
"@fragments-sdk/context": "0.8.1"
|
|
46
|
+
"@fragments-sdk/core": "3.4.0"
|
|
68
47
|
},
|
|
69
48
|
"devDependencies": {
|
|
49
|
+
"playwright": "^1.58.2",
|
|
70
50
|
"@types/node": "^22.0.0",
|
|
71
|
-
"convex": "^1.17.0",
|
|
72
51
|
"tsup": "^8.3.5",
|
|
73
|
-
"
|
|
74
|
-
"vitest": "^2.1.8",
|
|
75
|
-
"@fragments-sdk/extract": "0.2.1"
|
|
52
|
+
"vitest": "^2.1.8"
|
|
76
53
|
},
|
|
77
54
|
"scripts": {
|
|
78
55
|
"build": "tsup",
|
|
79
56
|
"dev": "tsup --watch",
|
|
80
57
|
"typecheck": "tsc --noEmit",
|
|
81
58
|
"test": "vitest run --passWithNoTests",
|
|
82
|
-
"clean": "rm -rf dist"
|
|
83
|
-
"index": "tsx scripts/index-components.ts"
|
|
59
|
+
"clean": "rm -rf dist"
|
|
84
60
|
}
|
|
85
61
|
}
|
package/dist/chunk-7D4SUZUM.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
var __create = Object.create;
|
|
2
|
-
var __defProp = Object.defineProperty;
|
|
3
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
8
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
9
|
-
}) : x)(function(x) {
|
|
10
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
11
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
12
|
-
});
|
|
13
|
-
var __commonJS = (cb, mod) => function __require2() {
|
|
14
|
-
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
15
|
-
};
|
|
16
|
-
var __copyProps = (to, from, except, desc) => {
|
|
17
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
18
|
-
for (let key of __getOwnPropNames(from))
|
|
19
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
20
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
21
|
-
}
|
|
22
|
-
return to;
|
|
23
|
-
};
|
|
24
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
25
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
26
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
27
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
28
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
29
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
30
|
-
mod
|
|
31
|
-
));
|
|
32
|
-
|
|
33
|
-
export {
|
|
34
|
-
__require,
|
|
35
|
-
__commonJS,
|
|
36
|
-
__toESM
|
|
37
|
-
};
|
|
38
|
-
//# sourceMappingURL=chunk-7D4SUZUM.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|