src — mcp

Module: src-mcp Cohesion: 0.80 Members: 0

src — mcp

The src/mcp module provides Code Buddy's integration with the Model Context Protocol (MCP). This protocol enables AI agents to discover and interact with tools, resources, and prompts provided by other services or applications.

The mcp module serves a dual purpose within Code Buddy:

  1. MCP Client: Code Buddy can connect to and utilize tools exposed by external MCP servers (e.g., web search, calendar integrations).
  2. MCP Server: Code Buddy can expose its own internal capabilities (file system, Git, Bash, AI agent, memory, sessions) as tools, resources, and prompts to other AI clients (e.g., VS Code extensions, other AI agents).

This module is critical for extending Code Buddy's functionality through external integrations and for allowing Code Buddy's powerful internal tools to be leveraged by other AI systems.

Core Concepts

The Model Context Protocol (MCP) defines a standardized way for AI agents to:

The mcp module implements both the client and server sides of this protocol, allowing Code Buddy to be a flexible participant in an AI-driven ecosystem.

Architecture Overview

The mcp module's architecture can be visualized as follows, highlighting its dual role as both a client and a server:

graph TD
    subgraph Code Buddy Application
        CB_Agent[CodeBuddyAgent]
        CB_Tools[Internal Tools: File, Git, Bash, Memory, Session, WebSearch]
    end

    subgraph MCP Module
        direction LR
        MCP_Client[MCPManager] -- Connects to --> External_MCP_Server
        MCP_Client -- Uses --> Transports[Transports: Stdio, HTTP, SSE]
        MCP_Client -- Manages --> Config[Config: loadMCPConfig]
        MCP_Client -- Handles Auth --> OAuth[OAuth: MCPOAuthManager]

        External_MCP_Client[External AI Client] -- Connects to --> MCP_Server[CodeBuddyMCPServer]
        MCP_Server -- Exposes --> CB_Agent
        MCP_Server -- Exposes --> CB_Tools
        MCP_Server -- Uses --> StdioServer[StdioServerTransport]
    end

    External_MCP_Server[External MCP Server]
    External_MCP_Client[External AI Client]

    style MCP_Client fill:#bbf,stroke:#333,stroke-width:2px
    style MCP_Server fill:#bbf,stroke:#333,stroke-width:2px

Key Components

MCPManager (client.ts)

The MCPManager class is the primary client-side component for interacting with external MCP servers. It acts as an orchestrator for multiple MCP connections.

Responsibilities:

Execution Flow (Adding a Server):

  1. addServer(config: MCPServerConfig) is called.
  2. A MCPTransport is created via createTransport(config.transport).
  3. An @modelcontextprotocol/sdk/client Client instance is created.
  4. The MCPTransport connects, returning an SDK Transport instance.
  5. The SDK Client connects using the SDK Transport.
  6. client.listTools() is called to discover available tools.
  7. Discovered tools are registered in MCPManager's internal tools map.
  8. A health check interval is started for the server.

CodeBuddyMCPServer (mcp-server.ts)

The CodeBuddyMCPServer class enables Code Buddy to act as an MCP server, exposing its internal capabilities to external AI clients.

Responsibilities:

Exposed Capabilities:

Configuration (config.ts)

This module handles the loading and saving of MCP server configurations.

Key Functions:

  1. ./.codebuddy/mcp.json (project-specific, committable)
  2. ./.codebuddy/settings.json (project-specific, user-managed)
  3. ~/.codebuddy/mcp.json (user-global)

It also resolves ${ENV_VAR} references in environment variables.

Transports (transports.ts)

This module defines the MCPTransport interface and concrete implementations for different communication methods.

Implementations:

OAuth (mcp-oauth.ts)

The MCPOAuthManager class provides robust support for OAuth 2.0 Authorization Code flow with PKCE, essential for authenticating with external MCP servers that require it.

Key Features:

Tool Auto-Discovery (mcp-auto-discovery.ts)

The MCPAutoDiscovery class helps manage the display and loading of tool descriptions, especially when many tools are available.

Purpose:

Key Methods:

Pre-configured Connectors (connectors.ts)

The ConnectorRegistry provides a curated list of pre-configured external MCP server connectors for popular services.

Features:

Legacy MCPClient (mcp-client.ts)

This class represents an older, manual implementation of an MCP client. While MCPManager is the recommended approach for new code (leveraging the SDK), MCPClient is still used by parts of the codebuddy-agent for its direct stdio process management and custom configuration loading.

Key Differences from MCPManager:

Integration Points

The mcp module integrates deeply with various other parts of the Code Buddy codebase:

Usage Patterns for Developers

Contributing to CodeBuddyMCPServer (Exposing new Code Buddy tools)

To expose a new Code Buddy capability as an MCP tool, resource, or prompt:

  1. Identify the capability: Determine which existing Code Buddy functionality you want to expose.
  2. Choose the type: Is it an action (tool), read-only data (resource), or a workflow template (prompt)?
  3. Create a registration module: If it's a new category, create a new mcp--tools.ts file (e.g., mcp-new-feature-tools.ts). Otherwise, add to an existing one.
  4. Define schema (for tools/prompts): Use zod to define the input arguments for your tool or prompt. This schema will be exposed to MCP clients.
  5. Implement the handler: Write an async function that takes the parsed arguments, calls the underlying Code Buddy logic, and returns the result in the MCP CallToolResult format (for tools) or PromptResult format (for prompts). For resources, return ResourceResult.
  6. Register with McpServer: In CodeBuddyMCPServer's registerTools() or registerAgentLayer() method, call this.mcpServer.tool(), this.mcpServer.resource(), or this.mcpServer.prompt() with your definition and handler.
  7. Lazy Load Dependencies: Ensure that heavy dependencies are await import()-ed inside the handler, not at the top level, to maintain fast startup.

Using MCPManager (Connecting to external MCP servers)

To integrate with a new external MCP server:

  1. Define MCPServerConfig: Create a configuration object specifying the server's name, transport type (stdio, http, sse), and connection details (command/args for stdio, URL for http/sse).
  2. Add to MCPManager: Call mcpManager.addServer(config). This will establish the connection, discover tools, and start health checks.
  3. Discover Tools: Use mcpManager.getTools() to retrieve a list of all available tools (including those from external servers). Remember that external tools are prefixed (e.g., mcp__brave-search__search).
  4. Call Tools: Invoke external tools using mcpManager.callTool(toolName, arguments_).
  5. OAuth (if required): If the external server requires OAuth, you'll need to integrate with MCPOAuthManager to obtain and manage tokens.

Configuration Management

Developers can manage MCP server configurations through:

This module forms a powerful bridge, allowing Code Buddy to both consume and provide AI-driven capabilities within a broader ecosystem.