-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add root-cms mcp server command #770
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
stevenle
wants to merge
2
commits into
main
Choose a base branch
from
codex/add-root-cms-mcp-command-for-mcp-server
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| import {loadRootConfig} from '@blinkk/root/node'; | ||
| import packageJson from '../package.json' assert {type: 'json'}; | ||
| import {RootCMSClient} from '../core/client.js'; | ||
| import { | ||
| fetchRootCmsDoc, | ||
| rootCmsGetDocInputJsonSchema, | ||
| rootCmsGetDocToolMetadata, | ||
| } from '../core/ai/tools/getDocTool.js'; | ||
|
|
||
| type ToolResponse = { | ||
| content: Array<{type: 'text'; text: string}>; | ||
| isError?: boolean; | ||
| }; | ||
|
|
||
| async function loadMcpSdk() { | ||
| const [{Server}, transportModule] = await Promise.all([ | ||
| import('@modelcontextprotocol/sdk/server/index.js'), | ||
| import('@modelcontextprotocol/sdk/server/node/index.js').catch(async () => | ||
| import('@modelcontextprotocol/sdk/server/stdio.js') | ||
| ), | ||
| ]); | ||
| const StdioServerTransport = | ||
| (transportModule as any).StdioServerTransport || | ||
| (transportModule as any).stdioServerTransport || | ||
| (transportModule as any).default; | ||
| if (!StdioServerTransport) { | ||
| throw new Error('Unable to load MCP stdio transport implementation.'); | ||
| } | ||
| return {Server, StdioServerTransport}; | ||
| } | ||
|
|
||
| function registerTool( | ||
| server: any, | ||
| definition: { | ||
| name: string; | ||
| description: string; | ||
| inputSchema: unknown; | ||
| }, | ||
| handler: (payload: unknown) => Promise<ToolResponse> | ||
| ) { | ||
| if (typeof server.tool === 'function') { | ||
| return server.tool(definition, handler); | ||
| } | ||
| if (typeof server.registerTool === 'function') { | ||
| return server.registerTool(definition, handler); | ||
| } | ||
| if (typeof server.addTool === 'function') { | ||
| return server.addTool(definition, handler); | ||
| } | ||
| throw new Error('Unsupported MCP SDK version: missing tool registration helper.'); | ||
| } | ||
|
|
||
| function formatDocForResponse(doc: unknown): ToolResponse { | ||
| return { | ||
| content: [ | ||
| { | ||
| type: 'text', | ||
| text: JSON.stringify(doc, null, 2), | ||
| }, | ||
| ], | ||
| }; | ||
| } | ||
|
|
||
| async function handleGetDocRequest( | ||
| cmsClient: RootCMSClient, | ||
| rawPayload: unknown | ||
| ): Promise<ToolResponse> { | ||
| try { | ||
| const result = await fetchRootCmsDoc(cmsClient, rawPayload); | ||
| if (!result.doc) { | ||
| return { | ||
| content: [ | ||
| { | ||
| type: 'text', | ||
| text: `Doc not found: ${result.collectionId}/${result.slug} (mode: ${result.mode})`, | ||
| }, | ||
| ], | ||
| isError: true, | ||
| }; | ||
| } | ||
| return formatDocForResponse(result.doc); | ||
| } catch (error) { | ||
| const message = | ||
| error instanceof Error ? error.message : 'Unknown error fetching doc.'; | ||
| return { | ||
| content: [ | ||
| { | ||
| type: 'text', | ||
| text: `Error fetching Root CMS doc: ${message}`, | ||
| }, | ||
| ], | ||
| isError: true, | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| export async function startMcpServer() { | ||
| const rootDir = process.cwd(); | ||
| const rootConfig = await loadRootConfig(rootDir, {command: 'root-cms'}); | ||
| const cmsClient = new RootCMSClient(rootConfig); | ||
|
|
||
| const {Server, StdioServerTransport} = await loadMcpSdk(); | ||
| const server = new Server({ | ||
| name: 'root-cms-mcp', | ||
| version: packageJson.version, | ||
| description: 'Expose Root CMS project data over the Model Context Protocol.', | ||
| }); | ||
|
|
||
| registerTool( | ||
| server, | ||
| { | ||
| name: rootCmsGetDocToolMetadata.name, | ||
| description: rootCmsGetDocToolMetadata.description, | ||
| inputSchema: rootCmsGetDocInputJsonSchema, | ||
| }, | ||
| async (payload: unknown) => { | ||
| const input = | ||
| (payload as any)?.input ?? | ||
| (payload as any)?.arguments ?? | ||
| payload; | ||
| return handleGetDocRequest(cmsClient, input); | ||
| } | ||
| ); | ||
|
|
||
| const transport = new StdioServerTransport(); | ||
| await server.connect(transport); | ||
| console.log('Root CMS MCP server listening on stdio. Press Ctrl+C to exit.'); | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| const shutdown = () => { | ||
| try { | ||
| if (typeof transport.close === 'function') { | ||
| transport.close(); | ||
| } | ||
| } catch (err) { | ||
| reject(err); | ||
| return; | ||
| } | ||
| resolve(); | ||
| }; | ||
| process.once('SIGINT', shutdown); | ||
| process.once('SIGTERM', shutdown); | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| import {z} from 'zod'; | ||
| import {DocMode, RootCMSClient, parseDocId} from '../../client.js'; | ||
|
|
||
| const DOC_MODES = ['draft', 'published'] as const satisfies DocMode[]; | ||
|
|
||
| export const rootCmsGetDocToolMetadata = { | ||
| name: 'root_cms.get_doc', | ||
| description: | ||
| 'Fetch a document from the current Root CMS project by collection and slug.', | ||
| } as const; | ||
|
|
||
| export const rootCmsGetDocInputSchema = z | ||
| .object({ | ||
| docId: z | ||
| .string() | ||
| .describe('Fully-qualified doc id in the format "<Collection>/<slug>".') | ||
| .optional(), | ||
| collectionId: z | ||
| .string() | ||
| .describe('Collection id (e.g. "Pages").') | ||
| .optional(), | ||
| slug: z.string().describe('Doc slug (e.g. "home").').optional(), | ||
| mode: z | ||
| .enum(DOC_MODES) | ||
| .default('draft') | ||
| .describe('Whether to fetch the draft or published version of the doc.'), | ||
| }) | ||
| .refine( | ||
| (value) => { | ||
| if (value.docId) { | ||
| return true; | ||
| } | ||
| return Boolean(value.collectionId && value.slug); | ||
| }, | ||
| { | ||
| message: | ||
| 'Provide either "docId" or both "collectionId" and "slug" for the doc to fetch.', | ||
| path: ['docId'], | ||
| } | ||
| ); | ||
|
|
||
| export type RootCmsGetDocInput = z.infer<typeof rootCmsGetDocInputSchema>; | ||
|
|
||
| export const rootCmsGetDocInputJsonSchema = { | ||
| type: 'object', | ||
| properties: { | ||
| docId: { | ||
| type: 'string', | ||
| description: | ||
| 'Fully-qualified doc id in the format "<Collection>/<slug>" (e.g. "Pages/home").', | ||
| }, | ||
| collectionId: { | ||
| type: 'string', | ||
| description: 'Collection id (e.g. "Pages").', | ||
| }, | ||
| slug: { | ||
| type: 'string', | ||
| description: 'Doc slug (e.g. "home").', | ||
| }, | ||
| mode: { | ||
| type: 'string', | ||
| enum: [...DOC_MODES], | ||
| description: 'Whether to fetch the draft or published version of the doc.', | ||
| default: 'draft', | ||
| }, | ||
| }, | ||
| oneOf: [ | ||
| { | ||
| required: ['docId'], | ||
| }, | ||
| { | ||
| required: ['collectionId', 'slug'], | ||
| }, | ||
| ], | ||
| additionalProperties: false, | ||
| } as const; | ||
|
|
||
| export interface RootCmsGetDocContext { | ||
| collectionId: string; | ||
| slug: string; | ||
| mode: DocMode; | ||
| } | ||
|
|
||
| export interface RootCmsGetDocResult extends RootCmsGetDocContext { | ||
| doc: unknown | null; | ||
| } | ||
|
|
||
| export function normalizeRootCmsGetDocInput( | ||
| rawInput: unknown | ||
| ): RootCmsGetDocContext { | ||
| const parsed = rootCmsGetDocInputSchema.parse(rawInput); | ||
| let collectionId = parsed.collectionId; | ||
| let slug = parsed.slug; | ||
| if (parsed.docId) { | ||
| const docInfo = parseDocId(parsed.docId); | ||
| collectionId = docInfo.collection; | ||
| slug = docInfo.slug; | ||
| } | ||
| if (!collectionId || !slug) { | ||
| throw new Error( | ||
| 'A collection id and slug are required to fetch a doc from Root CMS.' | ||
| ); | ||
| } | ||
| const mode: DocMode = parsed.mode ?? 'draft'; | ||
| return {collectionId, slug, mode}; | ||
| } | ||
|
|
||
| export async function fetchRootCmsDoc( | ||
| cmsClient: RootCMSClient, | ||
| rawInput: unknown | ||
| ): Promise<RootCmsGetDocResult> { | ||
| const context = normalizeRootCmsGetDocInput(rawInput); | ||
| const doc = await cmsClient.getDoc(context.collectionId, context.slug, { | ||
| mode: context.mode, | ||
| }); | ||
| return {...context, doc}; | ||
| } | ||
|
|
||
| export type GenkitTool = { | ||
| name: string; | ||
| description: string; | ||
| inputSchema: unknown; | ||
| outputSchema: unknown; | ||
| handler: (input: unknown) => Promise<unknown>; | ||
| }; | ||
|
|
||
| export function createRootCmsGetDocGenkitTool( | ||
| cmsClient: RootCMSClient | ||
| ): GenkitTool { | ||
| return { | ||
| name: rootCmsGetDocToolMetadata.name, | ||
| description: rootCmsGetDocToolMetadata.description, | ||
| inputSchema: rootCmsGetDocInputSchema, | ||
| outputSchema: z.any(), | ||
| async handler(input: unknown) { | ||
| const result = await fetchRootCmsDoc(cmsClient, input); | ||
| if (!result.doc) { | ||
| throw new Error( | ||
| `Doc not found: ${result.collectionId}/${result.slug} (mode: ${result.mode})` | ||
| ); | ||
| } | ||
| return result.doc; | ||
| }, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P1] Resolve MCP server when stdio closes
The CLI keeps the process alive by awaiting a promise that only resolves on
SIGINTorSIGTERM. When the MCP client simply closes the stdio transport (the common shutdown path for child processes), no signal is delivered, so the handler instartMcpServernever resolves and the server continues running as an orphaned process. That means every disconnect leaks a hangingroot-cms mcpprocess until it is manually killed. Consider also resolving the promise when the stdio transport closes or whenserver.connectcompletes, so the command exits automatically when its pipes are torn down.Useful? React with 👍 / 👎.