import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' import type { RepoProvider } from './core/contracts/index.js' import { LocalProvider } from './providers/local/index.js' import { withReadScope } from './providers/local/content-view.js' import { isToolAvailable, TOOL_REQUIREMENTS } from './tools/availability.js' /** * The provider shape tool handlers consume. Now that every provider * (Local, GitHub, GitLab) implements the full `RepoProvider`, tools can * depend on the shared surface directly — no private alias required. * Kept as a re-export so callers that already import `ToolProvider` do * not need to migrate. */ export type ToolProvider = RepoProvider import { registerContextTools } from './tools/context.js' import { registerSetupTools } from './tools/setup.js' import { registerModelTools } from './tools/model.js' import { registerContentTools } from './tools/content.js' import { registerVocabularyTools } from './tools/vocabulary.js' import { registerWorkflowTools } from './tools/workflow.js' import { registerReconcileTools } from './tools/reconcile.js' import { registerNormalizeTools } from './tools/normalize.js' import { registerBulkTools } from './tools/bulk.js' import { registerContentStatusTools } from './tools/content-status.js' import { registerDoctorTools } from './tools/doctor.js' import { registerMediaTools } from './tools/media.js' import packageJson from '../package.json' with { type: 'json' } /** * Default MCP `instructions` for a server whose tools are `available`. * A hint names only a tool the session registers: `contentrain_apply` is * `projectRoot`-gated, so a remote session (Studio's `/api/mcp/remote`) * is never told to preview it. Deliberately kept under 512 characters — * directory listings and client UIs truncate longer strings. */ export function defaultInstructions(available: (tool: string) => boolean): string { return 'Contentrain is git-native content governance: models define structure; ' + 'content is canonical JSON/Markdown on a dedicated branch. Start with ' + 'contentrain_status; call contentrain_describe_format before creating ' + 'models or content, and contentrain_describe before editing a model\'s ' + 'entries. Every write lands on an isolated cr/* branch and content_save ' + 'validates before committing. Destructive tools require confirm:true' + (available('contentrain_apply') ? '; preview contentrain_apply with dry_run:true first. ' : '. ') + 'Content decisions stay with the agent.' } /** * The instructions of a server with every tool registered (local stdio and * CLI flows). Override via `CreateServerOptions.instructions`; when omitted, * `createServer` sends `defaultInstructions` for its own tool surface. */ export const DEFAULT_INSTRUCTIONS = defaultInstructions(() => true) export interface CreateServerOptions { /** * Content provider — drives reads (and, in later phases, writes) through * a reader surface. Required when `projectRoot` is omitted. Accepts the * narrow `ToolProvider` shape so either `LocalProvider` or * `GitHubProvider` satisfies the contract. */ provider?: ToolProvider /** * Local project root. When the provider is a `LocalProvider`, its own * `projectRoot` is used as the fallback. Tools that require local disk * (normalize, setup, git submit/merge) are not registered when no * projectRoot is available. */ projectRoot?: string /** * MCP `instructions` string sent to clients in the `initialize` response. * Defaults to `defaultInstructions` for the registered tools (with every * tool available: `DEFAULT_INSTRUCTIONS`); pass an empty string to omit * instructions entirely. */ instructions?: string } /** * `McpServer` variant that silently skips registration for tools named in * `skipTools`. Register functions call `server.tool(...)` unconditionally; * this subclass is what keeps capability-gated tools out of `tools/list` * when the provider (or missing projectRoot) could never satisfy them. */ class CapabilityFilteredMcpServer extends McpServer { private readonly _skipTools: ReadonlySet constructor( serverInfo: ConstructorParameters[0], options: ConstructorParameters[1], skipTools: ReadonlySet, ) { super(serverInfo, options) this._skipTools = skipTools } // McpServer.tool has six overloads; a rest-args override is the only // signature that satisfies all of them. Skipped tools return undefined — // register functions discard the handle, so nothing downstream observes it. override tool(...args: unknown[]): ReturnType { if (this._skipTools.has(args[0] as string)) { return undefined as unknown as ReturnType } // One read scope per call: a local provider resolves where `.contentrain/` // is read from once per call and answers every read from it (#229). const handler = args.at(-1) if (typeof handler === 'function') { args[args.length - 1] = (...callArgs: unknown[]) => withReadScope(() => handler(...callArgs)) } return (McpServer.prototype.tool as (...toolArgs: unknown[]) => ReturnType).apply(this, args) } } /** * What clients show for this server at `initialize`: a display name, a home * page and icons. Same values as `server.json`, the registry entry; a test * keeps the two equal. */ export const SERVER_IDENTITY = { title: 'Contentrain', websiteUrl: 'https://ai.contentrain.io/packages/mcp', icons: [ { src: 'https://ai.contentrain.io/logo/contentrain-512.png', mimeType: 'image/png', sizes: ['512x512'] }, { src: 'https://ai.contentrain.io/favicon.svg', mimeType: 'image/svg+xml', sizes: ['any'] }, ], } /** * Create an MCP server instance with every *available* Contentrain tool * registered. * * Two signatures: * * - `createServer('/path/to/project')` — legacy stdio flow. A `LocalProvider` * is constructed under the hood; every tool keeps behaving exactly as it * did before phase 5.3. * - `createServer({ provider, projectRoot? })` — phase 5.3 flow. Any * `RepoProvider` (including `GitHubProvider`) drives reads and writes. If * the provider is a `LocalProvider` and `projectRoot` is omitted, the * provider's own `projectRoot` is used. * * Tool listing is capability-aware: tools whose requirements * (`TOOL_REQUIREMENTS`) cannot be met by the resolved provider + * projectRoot pair are not registered, so `tools/list` only advertises * tools that can actually succeed. With a `LocalProvider` (stdio and CLI * flows) all 23 core tools remain registered — behavior there is unchanged. */ export function createServer(projectRoot: string): McpServer export function createServer(opts: CreateServerOptions): McpServer export function createServer(input: string | CreateServerOptions): McpServer { const { provider, projectRoot, instructions } = resolveServerContext(input) const skipTools = new Set( Object.keys(TOOL_REQUIREMENTS).filter(name => !isToolAvailable(name, provider, projectRoot)), ) const sent = instructions ?? defaultInstructions(name => !skipTools.has(name)) const server = new CapabilityFilteredMcpServer( { name: 'contentrain-mcp', version: packageJson.version, ...SERVER_IDENTITY, }, { instructions: sent || undefined }, skipTools, ) registerContextTools(server, provider, projectRoot) registerSetupTools(server, provider, projectRoot) registerModelTools(server, provider, projectRoot) registerContentTools(server, provider, projectRoot) registerContentStatusTools(server, provider) registerVocabularyTools(server, provider) registerWorkflowTools(server, provider, projectRoot) registerReconcileTools(server, provider, projectRoot) registerNormalizeTools(server, provider, projectRoot) registerBulkTools(server, provider, projectRoot) registerDoctorTools(server, provider, projectRoot) registerMediaTools(server, provider, projectRoot) return server } function resolveServerContext(input: string | CreateServerOptions): { provider: ToolProvider projectRoot: string | undefined instructions: string | undefined } { if (typeof input === 'string') { return { provider: new LocalProvider(input), projectRoot: input, instructions: undefined } } const instructions = input.instructions if (input.provider) { let projectRoot = input.projectRoot // Structural, not nominal: any worktree-backed provider exposes a // projectRoot, and a test double should be able to as well. if (!projectRoot) { const maybeRoot = (input.provider as { projectRoot?: unknown }).projectRoot if (typeof maybeRoot === 'string') projectRoot = maybeRoot } return { provider: input.provider, projectRoot, instructions } } if (input.projectRoot) { return { provider: new LocalProvider(input.projectRoot), projectRoot: input.projectRoot, instructions } } throw new Error('createServer: either `provider` or `projectRoot` must be provided') }