# MCP Server Core Library Documentation

## Project Overview

MCP Server is a Qt/C++ implementation of the Model Context Protocol (MCP) server framework. The framework provides a full MCP protocol implementation and supports MCP clients over an HTTP transport layer.

### Key Features

- ✅ Full MCP protocol implementation: supports the MCP specification (version 2025-06-18)
- ✅ HTTP transport layer: based on HTTP/1.1, supports high concurrency
- ✅ Three core services: Tools, Resources, Prompts
- ✅ Configuration-driven: supports automatic JSON configuration loading and startup
- ✅ Flexible tool registration: supports both function-style and QObject-slot registrations
- ✅ Middleware support: provides a middleware mechanism for request preprocessing
- ✅ Session management: complete session lifecycle management
- ✅ Subscription notifications: supports change notifications for resources, tools, and prompts

## Architecture

### Overall Architecture

```
┌─────────────────────────────────────────────────────────┐
│                    Application Layer                    │
│  (MCPAutoServer / custom server implementations)        │
└────────────────────┬────────────────────────────────────┘
                     │
┌────────────────────▼────────────────────────────────────┐
│                    Server Interface Layer               │
│              (IMCPServer / MCPServer)                   │
└────────────────────┬────────────────────────────────────┘
                     │
      ┌──────────────┼──────────────┐
      │              │              │
┌─────▼─────┐  ┌─────▼─────┐  ┌─────▼──────────┐
│ Tool Service│ │Resource  │  │ Prompt Service │
│ (Tools)     │ │Service   │  │ (Prompts)      │
└─────┬──────┘  └────┬─────┘  └────┬──────────┘
      │              │              │
      └──────────────┼──────────────┘
                     │
┌────────────────────▼────────────────────────────────────┐
│                   Routing & Dispatch Layer              │
│  (MCPRouter / MCPRequestDispatcher / MCPContext)        │
└────────────────────┬────────────────────────────────────┘
                     │
┌────────────────────▼────────────────────────────────────┐
│                    Message Handling Layer               │
│  (MCPMessage / MCPServerMessage / MCPMessageSender)     │
└────────────────────┬────────────────────────────────────┘
                     │
┌────────────────────▼────────────────────────────────────┐
│                      Transport Layer                    │
│      (MCPHttpTransport / IMCPTransport)                 │
└─────────────────────────────────────────────────────────┘
```

### Core Modules

1. Server Layer (IMCPServer / MCPServer)
   - IMCPServer: unified server interface; manages server lifecycle (start, stop, running status) and provides access to the three core services.
   - MCPServer: core server implementation; coordinates component initialization and manages transport and session services.
   - MCPAutoServer: automatic startup helper; loads configurations from the MCPServerConfig directory and auto-binds tool handlers.

2. Service Layer
   - Tool Service (IMCPToolService / MCPToolService)
     - Registers and manages tools
     - Executes tool calls
     - Lists tools
     - Tool change notifications
     - Supports two registration approaches:
       1. Function-based registration using std::function
       2. QObject-slot-based registration (bind to QObject slots)
   - Resource Service (IMCPResourceService / MCPResourceService)
     - Registers and manages resources
     - Reads resource content
     - Lists resources
     - Resource change notifications
     - Supports resource types:
       1. File resources (load from filesystem)
       2. Content resources (generated by function)
       3. Wrapper resources (wrap QObject for dynamic content)
   - Prompt Service (IMCPPromptService / MCPPromptService)
     - Registers and manages prompts
     - Renders prompt templates (supports {{variable}} placeholders)
     - Lists prompts
     - Prompt change notifications

3. Routing Layer
   - MCPRouter: maps MCP method names to handlers; supports middleware and unified error handling.
   - MCPRequestDispatcher: parses client requests, routes them to handlers and builds responses.
   - MCPContext: request context wrapper for session and request parameters.

4. Message Layer
   - MCPMessage: base message; supports request, response, and notification types.
   - MCPServerMessage: server-side message wrapper; supports error responses.
   - MCPMessageSender: unified message sender; selects suitable send strategy based on message and transport type.

5. Transport Layer
   - MCPHttpTransport: HTTP transport implementation based on Qt's QTcpServer; supports HTTP/1.1 and thread-pool connection handling.
   - MCPHttpConnection: manages a single HTTP connection (parse request, build response).

6. Config Layer
   - IMCPServerConfig / MCPServerConfig: configuration interface and implementation.
     - Manages server configuration (port, name, version, etc.)
     - Loads configuration from a directory (supports Tools, Resources, Prompts subdirectories)
     - Saves configuration to directory

Configuration directory structure:
```
MCPServerConfig/
├── ServerConfig.json      # main configuration
├── Tools/                 # tool configuration directory
│   ├── calculator.json
│   └── ...
├── Resources/             # resource configuration directory
│   └── ...
└── Prompts/               # prompts configuration directory
    └── ...
```

## Quick Start

### 1. Basic Usage

Option 1 — Auto-start (recommended)

```cpp
#include <QCoreApplication>
#include "IMCPServer.h"
#include "MyExampleHandler.h"

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // Create the tool handler (must be created; MCPAutoServer finds it by objectName)
    MyExampleHandler* pHandler = new MyExampleHandler(qApp);
    pHandler->setObjectName("MyExampleHandler");

    // Auto-start the server (loads configuration from MCPServerConfig directory)
    StartAutoMCPServer();

    return app.exec();
}
```

Option 2 — Manual creation and configuration

```cpp
#include <QCoreApplication>
#include "IMCPServer.h"

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // Create the server instance
    auto pServer = IMCPServer::createServer();

    // Configure server
    auto pConfig = pServer->getConfig();
    pConfig->setPort(8888);
    pConfig->setServerName("MyServer");

    // Register a tool
    auto pToolService = pServer->getToolService();
    QJsonObject inputSchema = {
        {"type", "object"},
        {"properties", QJsonObject{{
            {"name", QJsonObject{{"type", "string"}}}
        }}}
    };
    QJsonObject outputSchema = {
        {"type", "object"},
        {"properties", QJsonObject{{
            {"result", QJsonObject{{"type", "string"}}}
        }}}
    };

    pToolService->add("greet", "Greet Tool", "A greeting tool",
        inputSchema, outputSchema,
        []() -> QJsonObject {
            QJsonObject result;
            result["content"] = QJsonArray{QJsonObject{{"type", "text"}, {"text", "Hello!"}}};
            return result;
        });

    // Start server
    pServer->start();

    return app.exec();
}
```

### 2. Creating a Tool Handler

A tool handler is a QObject-derived class that provides slot methods to handle tool calls:

```cpp
// MyExampleHandler.h
#pragma once
#include <QObject>
#include <QJsonObject>

class MyExampleHandler : public QObject
{
    Q_OBJECT
public:
    explicit MyExampleHandler(QObject* parent = nullptr);

public slots:
    // Tool handler method: parameter types must match inputSchema
    QJsonObject calculateOperation(double a, double b, const QString& operation);

    // Return type must be QJsonObject matching outputSchema
};
```

(Additional sections continue with configuration file examples, loading mechanism, best practices, handler resolver, and other detailed documentation — translated throughout the README.)