diff --git a/app/base-app.module.ts b/app/base-app.module.ts index 7b6b315..b65983d 100644 --- a/app/base-app.module.ts +++ b/app/base-app.module.ts @@ -14,7 +14,7 @@ import { S3Module } from '@shared/utils/s3/s3.module'; import { JobsModule } from '@shared/utils/jobs/jobs.module'; import { JobHandler } from '@shared/utils/jobs/job.types'; import { McpModule } from '@shared/mcp/mcp.module'; -import { McpConsent, McpTool } from '@shared/mcp/mcp.types'; +import { McpConsent, McpPrompt, McpTool } from '@shared/mcp/mcp.types'; import { getPinoConfig } from '@shared/config/pino.config'; import { AppController } from './app.controller'; import { AppService } from './app.service'; @@ -32,6 +32,8 @@ export interface BaseNraAppModuleOptions { mcpTools?: Type[]; /** MCP server instructions: what the app is and how its tools fit together. */ mcpInstructions?: string; + /** MCP prompt templates the user can pick in the AI app. */ + mcpPrompts?: McpPrompt[]; /** What the MCP login page says the connection gives access to. Defaults to read access to usage statistics. */ mcpConsent?: McpConsent; } @@ -55,7 +57,7 @@ export class BaseNraAppModule { options.entitiesModule, AuthModule.forRoot({ userInitModule }), YemotModule.register(options.yemotHandlerService), - ...(options.mcpTools?.length ? [McpModule.forRoot({ tools: options.mcpTools, instructions: options.mcpInstructions, consent: options.mcpConsent })] : []), + ...(options.mcpTools?.length ? [McpModule.forRoot({ tools: options.mcpTools, instructions: options.mcpInstructions, prompts: options.mcpPrompts, consent: options.mcpConsent })] : []), ], controllers: [AppController], providers: [ diff --git a/mcp/__tests__/mcp-server.factory.spec.ts b/mcp/__tests__/mcp-server.factory.spec.ts index fa4db8e..6e01ac5 100644 --- a/mcp/__tests__/mcp-server.factory.spec.ts +++ b/mcp/__tests__/mcp-server.factory.spec.ts @@ -2,7 +2,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { z } from 'zod'; import { buildMcpServer } from '../mcp-server.factory'; -import { McpTool, McpToolError } from '../mcp.types'; +import { McpPrompt, McpTool, McpToolError } from '../mcp.types'; describe('buildMcpServer', () => { const echo: McpTool = { @@ -13,9 +13,9 @@ describe('buildMcpServer', () => { }; const failing = (error: Error): McpTool => ({ ...echo, name: 'fail', handler: async () => Promise.reject(error) }); - const connect = async (tools: McpTool[], instructions?: string) => { + const connect = async (tools: McpTool[], instructions?: string, prompts?: McpPrompt[]) => { const [clientSide, serverSide] = InMemoryTransport.createLinkedPair(); - await buildMcpServer(tools, { userId: 7 }, instructions).connect(serverSide); + await buildMcpServer(tools, { userId: 7 }, instructions, prompts).connect(serverSide); const client = new Client({ name: 'test', version: '1' }); await client.connect(clientSide); return client; @@ -51,4 +51,22 @@ describe('buildMcpServer', () => { const hidden: any = await (await connect([failing(new Error('SQL broke'))])).callTool({ name: 'fail', arguments: {} }); expect(hidden).toMatchObject({ content: [{ type: 'text', text: 'Internal error' }], isError: true }); }); + + it('lists prompts and builds their message from the arguments', async () => { + const greet: McpPrompt = { + name: 'greet', + title: 'Greet', + description: 'Says hello', + argsSchema: { who: z.string(), tone: z.string().optional() }, + build: ({ who, tone }) => `Say hello to ${who}${tone ? ` (${tone})` : ''}`, + }; + const client = await connect([echo], undefined, [greet]); + const { prompts } = await client.listPrompts(); + expect(prompts).toEqual([expect.objectContaining({ + name: 'greet', title: 'Greet', description: 'Says hello', + arguments: [expect.objectContaining({ name: 'who', required: true }), expect.objectContaining({ name: 'tone', required: false })], + })]); + const { messages } = await client.getPrompt({ name: 'greet', arguments: { who: 'Dana' } }); + expect(messages).toEqual([{ role: 'user', content: { type: 'text', text: 'Say hello to Dana' } }]); + }); }); diff --git a/mcp/mcp-server.factory.ts b/mcp/mcp-server.factory.ts index 1242855..5b8932f 100644 --- a/mcp/mcp-server.factory.ts +++ b/mcp/mcp-server.factory.ts @@ -1,11 +1,11 @@ import { Logger } from '@nestjs/common'; import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { McpTool, McpToolContext, McpToolError } from './mcp.types'; +import { McpPrompt, McpTool, McpToolContext, McpToolError } from './mcp.types'; const logger = new Logger('Mcp'); /** One server per request (stateless transport); each tool runs as `ctx.userId`. */ -export function buildMcpServer(tools: McpTool[], ctx: McpToolContext, instructions?: string): McpServer { +export function buildMcpServer(tools: McpTool[], ctx: McpToolContext, instructions?: string, prompts: McpPrompt[] = []): McpServer { const server = new McpServer({ name: 'nra-stats', version: '1.0.0' }, instructions ? { instructions } : undefined); for (const tool of tools) { server.registerTool( @@ -25,5 +25,12 @@ export function buildMcpServer(tools: McpTool[], ctx: McpToolContext, instructio }, ); } + for (const prompt of prompts) { + server.registerPrompt( + prompt.name, + { title: prompt.title, description: prompt.description, argsSchema: prompt.argsSchema }, + (args: any) => ({ messages: [{ role: 'user' as const, content: { type: 'text' as const, text: prompt.build(args ?? {}) } }] }), + ); + } return server; } diff --git a/mcp/mcp.controller.ts b/mcp/mcp.controller.ts index 2199f6f..e88087a 100644 --- a/mcp/mcp.controller.ts +++ b/mcp/mcp.controller.ts @@ -2,7 +2,7 @@ import { Body, Controller, Delete, Get, Inject, Optional, Post, Request, Res } f import { Request as ExpressRequest, Response } from 'express'; import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; import { buildMcpServer } from './mcp-server.factory'; -import { MCP_INSTRUCTIONS, MCP_TOOL, McpTool } from './mcp.types'; +import { MCP_INSTRUCTIONS, MCP_PROMPTS, MCP_TOOL, McpPrompt, McpTool } from './mcp.types'; import { McpOAuthProvider } from './oauth/mcp-oauth.provider'; import { mcpBaseUrl, resourceMetadataUrl } from './oauth/mcp-auth.middleware'; @@ -16,6 +16,7 @@ export class McpController { private readonly oauth: McpOAuthProvider, @Inject(MCP_TOOL) private readonly tools: McpTool[], @Optional() @Inject(MCP_INSTRUCTIONS) private readonly instructions?: string | null, + @Optional() @Inject(MCP_PROMPTS) private readonly prompts?: McpPrompt[] | null, ) {} /** Streamable HTTP, stateless: a fresh server + transport per request, JSON responses, no sessions. */ @@ -35,6 +36,7 @@ export class McpController { this.tools, { userId: auth.extra.userId as number, baseUrl: mcpBaseUrl(req) ?? undefined }, this.instructions ?? undefined, + this.prompts ?? [], ); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); res.on('close', () => { diff --git a/mcp/mcp.module.ts b/mcp/mcp.module.ts index 73e6a24..c6ebff8 100644 --- a/mcp/mcp.module.ts +++ b/mcp/mcp.module.ts @@ -2,7 +2,7 @@ import { DynamicModule, MiddlewareConsumer, Module, NestModule, Provider, Type } import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from '@shared/entities/User.entity'; import { McpController } from './mcp.controller'; -import { DEFAULT_MCP_CONSENT, MCP_CONSENT, MCP_INSTRUCTIONS, MCP_TOOL, McpConsent, McpTool } from './mcp.types'; +import { DEFAULT_MCP_CONSENT, MCP_CONSENT, MCP_INSTRUCTIONS, MCP_PROMPTS, MCP_TOOL, McpConsent, McpPrompt, McpTool } from './mcp.types'; import { McpOAuthProvider } from './oauth/mcp-oauth.provider'; import { McpOAuthController } from './oauth/mcp-oauth.controller'; import { McpAuthMiddleware } from './oauth/mcp-auth.middleware'; @@ -11,6 +11,8 @@ export interface McpModuleOptions { tools: Type[]; /** Sent to every client on connect: what the app is and how to use its tools. */ instructions?: string; + /** Prompt templates the user can pick in the AI app. */ + prompts?: McpPrompt[]; /** What the login page says the connection gives access to. Defaults to read access to usage statistics. */ consent?: McpConsent; } @@ -38,6 +40,7 @@ export class McpModule implements NestModule { ...options.tools, toolAggregator, { provide: MCP_INSTRUCTIONS, useValue: options.instructions ?? null }, + { provide: MCP_PROMPTS, useValue: options.prompts ?? [] }, { provide: MCP_CONSENT, useValue: options.consent ?? DEFAULT_MCP_CONSENT }, ], }; diff --git a/mcp/mcp.types.ts b/mcp/mcp.types.ts index be86a11..85c1197 100644 --- a/mcp/mcp.types.ts +++ b/mcp/mcp.types.ts @@ -44,5 +44,21 @@ export interface McpTool { handler(input: any, ctx: McpToolContext): Promise; } +/** + * A prompt template on `/mcp` (prompts/list): a ready-made request the user picks in the AI app + * (often as a slash command). `build` turns the user's arguments into the message sent to the model. + * MCP prompt arguments are strings; mark optional ones with `.optional()`. + */ +export interface McpPrompt { + name: string; + title?: string; + description: string; + argsSchema?: Shape; + build(args: Record): string; +} + +/** DI token for the app's MCP prompts. */ +export const MCP_PROMPTS = 'MCP_PROMPTS'; + /** An error whose message is shown to the user (nothing found, no active game). Other errors are hidden. */ export class McpToolError extends Error {}