# MCP Server Architecture
## Goals
- Provide a production-ready Model Context Protocol (MCP) server that can call the OpenAI API securely and efficiently.
- Showcase three concrete scenarios:
1. **OpenAI connectivity demo** – basic chat completion proxy with tracing.
2. **MCP tool capability** – expose a structured tool (e.g., knowledge search) through MCP.
3. **Extensibility demo** – allow external modules to register their own tools without touching core logic.
- Emphasize clean abstractions, error handling, and commercial readiness (observability, config safety, typing, testability).
## High-level Architecture
```
┌────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐
│ HTTP / CLI / │ │ MCP Server Core │ │ OpenAI │
│ MCP Client │◀────▶│ (Transport + Tools)│──────▶│ API (chat, response)│
└────────────────┘ └──────────────────────┘ └──────────────────────┘
▲ ▲ ▲ ▲
│ │ │ │
│ ┌────────┘ │ └───────────────┐
│ │ │ │
│ ┌────────┴──────┐ ┌──┴─────────────┐ ┌──┴───────────────┐
│ │ Tool Registry │ │ Observability │ │ Config / Secrets │
│ │ + Lifecycle │ │ + Diagnostics │ │ (dotenv / env) │
│ └───────────────┘ └────────────────┘ └──────────────────┘
│
▼
Demo runners (CLI scripts, tests)
```
## Key Modules
| Module | Responsibility |
| --- | --- |
| `src/config/env.ts` | Normalize environment variables, validate required values, load `.env`. |
| `src/clients/openaiClient.ts` | Thin wrapper around OpenAI SDK v4 with retry, timeout, and telemetry hooks. |
| `src/mcp/server.ts` | Bootstraps MCP transport (stdio by default) and wires tool registry + OpenAI client. |
| `src/mcp/tools/baseTool.ts` | Abstract base class defining `name`, `schema`, `execute` contract. |
| `src/mcp/tools/builtin/*` | Concrete tool implementations (e.g., knowledge search, summarizer). |
| `src/mcp/registry.ts` | Registers tools, enforces uniqueness, supports dynamic plugin loading. |
| `src/demos/openaiPing.ts` | Script showing direct OpenAI call via server service. |
| `src/demos/toolInvocation.ts` | Script exercising an MCP tool end-to-end. |
| `src/demos/extensibility.ts` | Shows registering a tool at runtime (e.g., mock finance quote). |
| `src/demos/uiServer.ts` | Minimal HTTP server powering the browser-based demo UI. |
| `public/ui-demo.html` | Static HTML/JS page that calls OpenAI and MCP endpoints. |
| `tests/**/*` | Unit tests for registry, OpenAI wrapper, and demo flows. |
## Data Flow
1. **Startup** – `src/index.ts` loads `env`, constructs `OpenAIClient`, initializes `ToolRegistry`, registers built-ins, and starts the MCP transport.
2. **Client request** – MCP client sends `request` (chat or tool invocation) over transport -> parsed by server core.
3. **Routing** – Chat requests call into `OpenAIClient`. Tool invocations lookup tool implementation via `ToolRegistry`.
4. **Execution** – Tools may call OpenAI or other services. Responses are serialized back to MCP client.
5. **Observability** – Structured logs (pino), metrics hooks, and error boundaries ensure production-readiness.
## Extensibility Strategy
- **Tool Registry Plugins**: Accepts modules that export `ToolDefinition`. Hot-loadable via configuration or CLI flag.
- **Middleware Hooks**: Pre/post handlers to decorate requests (logging, auth, rate limits).
- **Provider Abstraction**: `OpenAIClient` implements `LLMProvider` interface. Future providers can be dropped in.
## Demo Scenarios
1. **`openai-ping`** – CLI command hitting `/demos/openaiPing.ts`, prints latency and completion text. Validates API keys and retries.
2. **`knowledge-search` tool** – Exposes a YAML-backed knowledge base as MCP tool. Demo script sends a tool call and prints structured result.
3. **Browser UI** – Launches an interactive page to test both OpenAI chat and the knowledge-search tool via REST wrappers.
4. **`plug-in tool`** – Demonstrates loading a custom module from `examples/plugins/stockQuoteTool.ts` without modifying core.
## Non-Functional Requirements
- TypeScript strict mode, ESLint, Prettier.
- npm (default, pnpm compatible) with lockfile for deterministic installs.
- Unit tests via Vitest.
- `.env.example` with documented variables.
- Dynamic plugin loader via `MCP_TOOL_MODULES` env or runtime API to keep core immutable.
- Container-ready (`Dockerfile`) for deployment.
This architecture will guide implementation to meet the user's requirements while keeping the codebase maintainable and enterprise-ready.