Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions app/base-app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -32,6 +32,8 @@ export interface BaseNraAppModuleOptions {
mcpTools?: Type<McpTool>[];
/** 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;
}
Expand All @@ -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: [
Expand Down
24 changes: 21 additions & 3 deletions mcp/__tests__/mcp-server.factory.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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;
Expand Down Expand Up @@ -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' } }]);
});
});
11 changes: 9 additions & 2 deletions mcp/mcp-server.factory.ts
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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;
}
4 changes: 3 additions & 1 deletion mcp/mcp.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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. */
Expand All @@ -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', () => {
Expand Down
5 changes: 4 additions & 1 deletion mcp/mcp.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -11,6 +11,8 @@ export interface McpModuleOptions {
tools: Type<McpTool>[];
/** 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;
}
Expand Down Expand Up @@ -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 },
],
};
Expand Down
16 changes: 16 additions & 0 deletions mcp/mcp.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,21 @@ export interface McpTool<Shape extends ZodRawShape = ZodRawShape> {
handler(input: any, ctx: McpToolContext): Promise<unknown>;
}

/**
* 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<Shape extends ZodRawShape = ZodRawShape> {
name: string;
title?: string;
description: string;
argsSchema?: Shape;
build(args: Record<string, string | undefined>): 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 {}
Loading