Aller au contenu principal

MCP (Model Context Protocol) Integration

This document describes the MCP server integration in the Baldr API, which exposes the API's capabilities to Large Language Models (LLMs).

Overview

The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs. This integration allows LLMs to interact with your Baldr API through a standardized interface.

Architecture

Components

  1. MCP Service (src/services/mcp.service.ts)

    • Core MCP server implementation
    • Manages tools, resources, and prompts
    • Handles MCP protocol requests
  2. MCP Configuration (src/configs/mcp.config.ts)

    • Defines available tools (API operations)
    • Registers resources (documentation, schemas)
    • Sets up prompts (common tasks)
  3. MCP Server Entry Point (src/mcp-server.ts)

    • Standalone server process
    • Connects to database
    • Initializes MCP capabilities
  4. HTTP Interface (src/controllers/mcp.controller.ts)

    • Optional HTTP endpoints for testing
    • Status and information endpoints
    • Mounted at /api/mcp

Running the MCP Server

Development Mode

npm run mcp:dev

Production Mode

npm run build
npm run mcp

Available Capabilities

Tools

Tools are functions that LLMs can call to interact with your API:

  1. get_api_health

    • Check API health status
    • No parameters required
  2. list_modules

    • List all available modules
    • Parameters: includeInactive (boolean, optional)
  3. query_collection

    • Query MongoDB collections
    • Parameters:
      • collection (string, required): Collection name
      • filter (object, optional): MongoDB filter
      • limit (number, optional): Result limit
  4. get_api_stats

    • Get API usage statistics
    • Parameters: timeRange (string, optional): e.g., '24h', '7d', '30d'

Resources

Resources provide contextual information:

  • baldr://api/documentation - API documentation
  • baldr://database/schema - Database schema
  • baldr://api/endpoints - List of endpoints

Prompts

Pre-defined prompts for common tasks:

  • analyze_api_performance - Analyze and optimize API performance
  • debug_error - Help debug API errors

Configuring MCP Clients

Your project already includes .vscode/mcp.json for VS Code integration:

{
"servers": {
"BaldrApi": {
"type": "stdio",
"command": "node",
"args": [
"/home/romain/Dev/projects/BaldrTs/dist/mcp-server.js"
],
"env": {
"NODE_ENV": "development"
}
}
},
"inputs": []
}

Usage in VS Code:

  1. Build your project: npm run build
  2. Open Copilot Chat (Ctrl+Shift+I or Cmd+Shift+I)
  3. Use @BaldrApi to interact with your API tools

Example:

@BaldrApi check the health status
@BaldrApi list all modules

Claude Desktop Configuration (Alternative)

If you want to use Claude Desktop instead, add to your Claude Desktop config (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):

{
"mcpServers": {
"baldr-api": {
"command": "node",
"args": ["/path/to/BaldrTs/dist/mcp-server.js"],
"env": {
"NODE_ENV": "production"
}
}
}
}

Other MCP Clients

The server uses stdio transport, so any MCP-compatible client can connect:

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const transport = new StdioClientTransport({
command: "node",
args: ["/path/to/dist/mcp-server.js"],
});

const client = new Client({
name: "my-client",
version: "1.0.0",
}, {
capabilities: {},
});

await client.connect(transport);

Adding Custom Tools

To add new tools to the MCP server, edit src/configs/mcp.config.ts:

mcpService.registerTool(
"my_custom_tool",
"Description of what the tool does",
{
type: "object",
properties: {
param1: {
type: "string",
description: "Parameter description",
},
},
required: ["param1"],
},
async (args: { param1: string }) => {
// Tool implementation
return { result: "success" };
}
);

HTTP Testing Interface

For testing purposes, MCP status and info are available via HTTP:

# Check MCP server status
curl http://localhost:3000/api/mcp/status

# Get MCP server information
curl http://localhost:3000/api/mcp/info

# List tools (requires authentication)
curl http://localhost:3000/api/mcp/tools \
-H "Authorization: Bearer YOUR_TOKEN"

Security Considerations

  1. Authentication: The HTTP interface can use your existing auth middleware
  2. Stdio Transport: The MCP server uses stdio, which is secure for local/trusted environments
  3. Access Control: Consider limiting which operations are exposed via MCP
  4. Logging: All MCP operations are logged via Pino logger

Extending the Integration

Adding Resources

mcpService.registerResource(
"baldr://custom/resource",
"Resource Name",
"Resource description",
"application/json"
);

Adding Prompts

mcpService.registerPrompt(
"custom_task",
"Description of the task",
[
{ name: "param1", description: "Parameter description", required: true },
]
);

Troubleshooting

MCP Server Won't Start

  1. Check environment variables are properly configured
  2. Ensure database connection is successful
  3. Check logs: MCP server uses Pino logger

Tools Not Appearing

  1. Verify tools are registered in mcp.config.ts
  2. Check MCP client is properly connected
  3. Look for errors in server logs

Connection Issues

  1. Ensure stdio transport is properly configured
  2. Check file paths in client configuration
  3. Verify Node.js version compatibility

References