Content
# OH-MCPStack
OH-MCPStack is a native MCP (Model Context Protocol) protocol stack prototype project for **OpenHarmony / Ubiquitous Operating System**, corresponding to the first topic: **Design of a native MCP protocol stack for ubiquitous operating systems**.
The project's core goal is to sink the MCP capability from the upper-layer Agent framework to the system user-state service `mcpd`, unify the tool discovery, tool invocation, caching, security, and statistics between Agent and MCP Server, thereby reducing repeated development costs, decreasing context transmission overhead, and improving throughput in high-frequency tool invocation scenarios.
> The current implementation is a C++ user-state system service prototype, providing an OpenHarmony integration skeleton. The project does not modify the kernel and adopts a more easily landed user-state system service route.
## 1. Problems Solved by the Project
Ordinary MCP applications are typically:
```text
Agent / LangChain / HelloAgents
|
v
MCP Server
|
v
Tool / API / Data Source
```
This approach has several issues:
1. Each Agent framework maintains its own MCP call logic, which can be easily duplicated;
2. `tools/list` returns a complete tool schema, occupying a large amount of LLM context;
3. High-frequency repeated tool invocations lack system-level caching;
4. Authentication, permission control, and security restrictions are scattered in the application layer;
5. In multi-Agent high-concurrency scenarios, the backend MCP Server pressure is larger.
OH-MCPStack sinks the MCP protocol stack as a system service:
```text
Agent / LangChain / HelloAgents
|
v
mcpd System MCP Service
|
v
MCP Server / Tool Server
```
`mcpd` is responsible for unified proxy, caching, security, and statistics, and the upper-layer Agent only needs to access the unified MCP entrance provided by the system.
## 2. Current Implemented Capabilities
| Capability | Status | Description |
|---|---|---|
| C++ MCP Protocol Stack Prototype | Completed | `cpp/mcpd` |
| Mock MCP Server | Completed | Simulate Gaode Map MCP tool |
| `tools/list` Forwarding | Completed | Support complete and compact return |
| `tools/call` Forwarding | Completed | Support tool invocation proxy |
| Schema Caching | Completed | Generate `schema_id`, reduce repeated schema transmission |
| Compact Tool Description | Completed | Reduce Agent context occupation |
| Tool Result Caching | Completed | Cache tool repeated invocation directly hit `mcpd` |
| Token Authentication | Completed | `X-Agent-Token` |
| HMAC-SHA256 Request Signature | Completed | `X-Agent-Signature` / `X-Agent-Timestamp` / `X-MCP-Nonce` |
| Tool-Level ACL | Completed | Different tokens have different tool permissions |
| Nonce Replay Prevention | Completed | `X-MCP-Nonce` |
| Request Body Size Limitation | Completed | Prevent large request body attacks |
| `/healthz` Health Check | Completed | Service status check |
| `/stats` Statistics Interface | Completed | Cache, security, request statistics |
| Observable Metrics | Completed | `/metrics` Prometheus text metrics |
| Performance Test Script | Completed | Direct MCP vs mcpd |
| Security Test Script | Completed | Authentication, ACL, replay, large packet |
| Travel Planning End-to-End Demo | Completed | Align HelloAgents / Gaode MCP reference case |
| OpenHarmony Integration Skeleton | Completed | `openharmony/` |
## 3. Overall Architecture
```mermaid
flowchart TD
A["Agent / Client"] --> B["mcpd :18080"]
B --> C["Token Authentication"]
B --> D["ACL Tool Permission"]
B --> E["Schema Caching"]
B --> F["Tool Result Caching"]
B --> G["Nonce Replay Prevention"]
B --> H["Request Size Limitation"]
B --> I["Statistics /stats"]
B --> J["Mock MCP Server :18081"]
J --> K["amap.maps_weather"]
J --> L["amap.maps_text_search"]
J --> M["amap.maps_direction_transit_integrated_by_address"]
J --> N["amap.hotel_search"]
J --> O["amap.restaurant_search"]
```
Default ports:
| Service | Address | Description |
|---|---|---|
| `mcpd` | `http://127.0.0.1:18080` | System MCP service |
| Mock MCP Server | `http://127.0.0.1:18081` | Backend MCP tool service |
| RPC Interface | `/rpc` | JSON-RPC POST interface |
| Health Check | `/healthz` | GET interface |
| Statistics Interface | `/stats` | GET interface |
### 3.1 mcpd Module Split
`mcpd` has been split from a single-file prototype into multiple modules:
```text
cpp/mcpd/
main.cpp Startup parameters, configuration loading, and HTTP Server entrance
state.h Core state, policy structure, and module interface declaration
config.cpp Configuration file parsing, default Agent/service installation
router.cpp Upstream MCP service registration, tool name prefix routing
discovery.cpp tools/list compact, schema caching, progressive tool search
cache.cpp Result caching, TTL, LRU, invalidate/clear
handler.cpp JSON-RPC method distribution, security check, statistics interface
security.cpp HMAC-SHA256 request signature
```
This allows for clear visibility into the protocol stack's composition of configuration, routing, caching, security, and tool discovery sub-modules.
## 4. Quick Start
### 4.1 Environment Requirements
This project only depends on the system's compiler and CMake.
Recommended environment:
| Environment | Requirements |
|---|---|
| macOS | Apple Clang / CMake |
| Linux | g++ / CMake |
| OpenHarmony | Currently provides integration skeleton, and will be integrated into the source tree compilation later |
Check dependencies:
```bash
g++ --version
cmake --version
```
macOS can also use the system's `clang++`.
### 4.2 Compilation
```bash
cd /Users/wangyue/harmony/oh-mcpstack
./scripts/build_cpp.sh
```
On Linux servers, you can specify the compiler:
```bash
CXX=g++ ./scripts/build_cpp.sh
```
### 4.3 Start Service
You can run the smoke script directly, which will automatically compile, start `mock_mcp_server` and `mcpd`, and execute basic calls:
```bash
./scripts/run_cpp_smoke.sh
```
If you need to start manually:
```bash
./build/cpp/mock_mcp_server --port 18081
./build/cpp/mcpd --port 18080 --upstream http://127.0.0.1:18081/rpc
```
Configuration file startup:
```bash
./build/cpp/mcpd --config configs/mcpd.demo.json
```
`configs/mcpd.demo.json` decouples service registration, Agent token, ACL, cache limit, and security parameters from C++ code, making it easy to switch and deploy on OpenHarmony devices, edge nodes, and local pressure test environments.
### 4.4 Progressive Tool Discovery
In addition to the standard `tools/list`, `mcpd` also provides two system extension interfaces:
- `ohmcp/tools.search`: Returns a small number of related tools based on task keywords, avoiding loading all tool descriptions into the context at once;
- `ohmcp/tools.get_schema`: Obtain the complete `inputSchema/outputSchema` on demand based on `schema_id` or tool name.
Test:
```bash
./scripts/test_cpp_progressive_discovery.sh
```
After starting the service, you can access:
```bash
curl http://127.0.0.1:18080/healthz
curl http://127.0.0.1:18080/stats
curl http://127.0.0.1:18080/metrics
```
> Note: `/rpc` is a JSON-RPC POST interface, not a webpage. Browsers directly opening `http://127.0.0.1:18081/rpc` usually won't display meaningful content.
## 5. Example Invocation
### 5.1 Query Tool List
```bash
curl -s http://127.0.0.1:18080/rpc \
-H 'Content-Type: application/json' \
-H 'X-Agent-Token: demo-token' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"compact":true}}'
```
### 5.2 Invoke Weather Tool
```bash
curl -s http://127.0.0.1:18080/rpc \
-H 'Content-Type: application/json' \
-H 'X-Agent-Token: demo-token' \
-H 'X-MCP-Nonce: demo-001' \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"amap.maps_weather","arguments":{"city":"Suzhou"}}}'
```
### 5.3 View Statistics Information
```bash
curl -s http://127.0.0.1:18080/stats
```
## 6. MCP Tool Collection
The current Mock MCP Server provides 5 travel planning tools to align with the competition reference case of HelloAgents travel planning assistant and Gaode MCP tool invocation scenarios.
| Tool Name | Effect |
|---|---|
| `amap.maps_weather` | Query city weather |
| `amap.maps_text_search` | Search scenic spots / POI |
| `amap.maps_direction_transit_integrated_by_address` | Query cross-city routes |
| `amap.hotel_search` | Search hotels |
| `amap.restaurant_search` | Search restaurants |
Tool metadata includes:
```text
name
title
description
version
category
inputSchema
outputSchema
annotations
x-ohmcp
```
Where `x-ohmcp` is an extended field for this project, used to describe system-level optimization capabilities:
```json
{
"cacheable": true,
"cacheTtlMs": 60000,
"requiredPermission": "tool:weather",
"securityLevel": "normal"
}
```
## 7. Testing and Reproduction
### 7.1 Complete Test Command
```bash
cd /Users/wangyue/harmony/oh-mcpstack
./scripts/build_cpp.sh
./scripts/run_cpp_smoke.sh
./scripts/test_cpp_context_efficiency.sh
./scripts/test_cpp_result_cache.sh
./scripts/test_cpp_cache_controls.sh
./scripts/test_cpp_multi_service_router.sh
./scripts/test_cpp_security.sh
N=3000 ./scripts/bench_cpp_performance.sh
./scripts/run_trip_planner_demo.sh
```
Linux server:
```bash
CXX=g++ ./scripts/build_cpp.sh
CXX=g++ ./scripts/run_cpp_smoke.sh
CXX=g++ ./scripts/test_cpp_context_efficiency.sh
CXX=g++ ./scripts/test_cpp_result_cache.sh
CXX=g++ ./scripts/test_cpp_cache_controls.sh
CXX=g++ ./scripts/test_cpp_multi_service_router.sh
CXX=g++ ./scripts/test_cpp_security.sh
CXX=g++ N=3000 ./scripts/bench_cpp_performance.sh
CXX=g++ ./scripts/run_trip_planner_demo.sh
```
### 7.2 Test Script Description
| Script | Effect |
|---|---|
| `scripts/build_cpp.sh` | Compile C++ prototype |
| `scripts/run_cpp_smoke.sh` | Functional smoke test |
| `scripts/test_cpp_context_efficiency.sh` | Test tools/list context length optimization |
| `scripts/test_cpp_result_cache.sh` | Test tool result caching |
| `scripts/test_cpp_cache_controls.sh` | Test cache hash key, manual invalidation, clearing, LRU limit |
| `scripts/test_cpp_multi_service_router.sh` | Test multi-MCP service routing, service switching, service-level ACL |
| `scripts/test_cpp_security.sh` | Test authentication, ACL, nonce, anti-large packet |
| `scripts/bench_cpp_performance.sh` | Performance benchmark |
| `scripts/bench_multi_agent.sh` | Multi-Agent concurrent pressure test |
| `scripts/bench_edge_docker.sh` | Docker resource-constrained edge node test |
| `scripts/run_trip_planner_demo.sh` | End-to-end travel planning demo |
## 8. Phase Test Results
Complete test report see:
```text
docs/test_report.md
```
### 8.1 Context Length Optimization
| Object | Return Bytes |
|---|---:|
| Direct MCP Full | 5070 bytes |
| mcpd Full | 5387 bytes |
| mcpd Compact | 2379 bytes |
Optimization effect:
| Indicator | Result |
|---|---:|
| mcpd Compact relative to Direct MCP reduction | 53.08% |
| mcpd Compact relative to mcpd Full reduction | 55.84% |
This result corresponds to the "Optimize context length, improve communication efficiency by 10%" requirement in the competition.
### 8.2 Tool Result Caching
| Indicator | Result |
|---|---:|
| First same tool invocation `cached=false` quantity | 1 |
| Second same tool invocation `cached=true` quantity | 1 |
| `/stats` in result cache hits | 1 |
| `/stats` in result cache misses | 2 |
### 8.3 Security Test
| Test Item | Expected Status Code | Result |
|---|---:|---|
| No token request | 401 | Pass |
| Incorrect token request | 401 | Pass |
| ACL insufficient permissions | 403 | Pass |
| Nonce first request | 200 | Pass |
| Nonce replay request | 409 | Pass |
| Large request body | 413 | Pass |
### 8.4 Performance Benchmark
Server environment `N=3000` test results:
| Scenario | Request Number | QPS |
|---|---:|---:|
| Direct MCP Baseline | 3000 | 357.359 |
| mcpd Cache Miss | 3000 | 293.838 |
| mcpd Cache Hit | 3000 | 6141.31 |
Optimization effect:
| Indicator | Result |
|---|---:|
| mcpd Cache Hit relative to Direct MCP QPS improvement | 1618.53% |
| mcpd Cache Hit relative to mcpd Cache Miss QPS improvement | 1990.03% |
Note: When caching is not hit, `mcpd` has an additional layer of proxy, which may be slower than direct MCP connection; the performance benefit of this project is mainly reflected in high-frequency repeated queries, cacheable tools, and multi-Agent shared cache scenarios.
### 8.5 Multi-Agent Concurrent Pressure Test
Server environment simulates 10, 50, 100 Agents concurrent invocation of MCP tools, each Agent sends 200 requests. 100 Agent scenario results:
| Scenario | Total Request Number | QPS | Average Delay | P95 | P99 | Failed Number |
|---|---:|---:|---:|---:|---:|---:|
| Direct MCP | 20000 | 416.63 | 239.37 ms | 244.24 ms | 245.71 ms | 0 |
| mcpd Cache Miss | 20000 | 345.44 | 288.51 ms | 363.31 ms | 372.40 ms | 0 |
| mcpd Cache Hit | 20000 | 4536.95 | 21.94 ms | 22.32 ms | 23.71 ms | 0 |
Under 100 Agents, `mcpd Cache Hit` relative to ordinary MCP direct connection QPS improvement 988.96%, average delay reduction 90.83%. Detailed report see `docs/multi_agent_benchmark.md`.
### 8.6 Docker Resource-Constrained Edge Test
Using Docker to limit CPU and memory to simulate edge nodes. 50 Agent scenario results:
| Environment | CPU / Memory | Direct MCP QPS | mcpd Cache Hit QPS | Average Delay Reduction | Failed Number |
|---|---|---:|---:|---:|---:|
| Edge-1 | 1 CPU / 512 MB | 440.35 | 1531.80 | 71.28% | 0 |
| Edge-2 | 2 CPU / 1 GB | 438.91 | 5180.04 | 91.58% | 0 |
Detailed report see `docs/resource_limited_test.md`.
## 9. End-to-End Demo
This project provides a travel planning demo:
```bash
./scripts/run_trip_planner_demo.sh
```
Demo task:
```text
Travel planning from Shanghai to Suzhou for 3 days and 2 nights
```
Called tools:
1. Weather query;
2. Route planning;
3. Scenic spot search;
4. Hotel search;
5. Restaurant search.
This demo shows how the Agent application can uniformly call multiple MCP tools through `mcpd`, and reuse system-level caching and security capabilities.
---
## 10. OpenHarmony Integration Solution
The OpenHarmony integration framework is located in:
```text
openharmony/
```
Main files:
| File | Function |
|---|---|
| `openharmony/services/mcpd/BUILD.gn` | OpenHarmony GN build template |
| `openharmony/services/mcpd/bundle.json` | Component configuration |
| `openharmony/services/mcpd/init/mcpd.cfg` | init startup configuration |
| `openharmony/services/mcpd/mcpd_main.cpp` | Service entry template |
| `openharmony/interfaces/innerkits/include/imcp_service.h` | C++ InnerKit interface draft |
| `openharmony/interfaces/kits/arkts/oh_mcpstack.d.ts` | ArkTS Kit interface draft |
The current user-mode system service approach is adopted instead of the kernel module approach, because:
1. MCP is an application-layer JSON-RPC/tool call protocol, which is more suitable for user-mode service hosting;
2. User-mode services are easier to debug, upgrade, and integrate with the Agent framework;
3. Capabilities can be exposed through OpenHarmony init, system services, InnerKit, and ArkTS Kit;
4. Avoid processing complex JSON, network, and permission logic in the kernel.
For details, see:
```text
docs/openharmony_integration.md
```
---
## 11. Repository Structure
```text
cpp/
common/ HTTP, JSON, MCP basic libraries
mock_mcp_server/ Simulated Gaode MCP Server
mock_calendar_server/ Simulated calendar MCP Server
mcpd/ System MCP service prototype
client/ C++ command-line client
bench/ Performance test program
scripts/
build_cpp.sh
run_cpp_smoke.sh
test_cpp_context_efficiency.sh
test_cpp_result_cache.sh
test_cpp_cache_controls.sh
test_cpp_multi_service_router.sh
test_cpp_security.sh
bench_cpp_performance.sh
run_trip_planner_demo.sh
docs/
competition_requirements.md
design.md
test_plan.md
test_report.md
openharmony_integration.md
performance_benchmark.md
multi_agent_benchmark.md
resource_limited_test.md
security_tests.md
context_efficiency_test.md
result_cache.md
trip_planner_demo.md
reference_cases.md
tool_metadata.md
openharmony/
services/mcpd/
interfaces/innerkits/
interfaces/kits/arkts/
```
---
## 12. Correspondence with Competition Requirements
| Competition Requirements | Current Implementation |
|---|---|
| System-native MCP protocol stack | C++ user-mode `mcpd` service + OpenHarmony integration framework |
| Reduce intermediate layer performance loss | System-level unified proxy, tool schema caching, result caching |
| Performance improvement of 10% | Cache hit scenario QPS improvement of 1618.53% |
| Optimize context length by 10% | `tools/list` compact return reduces 53.08% of bytes |
| Support high-concurrency Agent | Completed 10/50/100 Agent concurrent pressure test |
| Built-in security mechanism | token, ACL, nonce, anti-large packet, statistics |
| Multi-Agent/edge node scenario | Completed multi-Agent concurrent test and Docker resource-limited test |
| End-to-end application case | Travel planning demo |
| Open-source code and documentation | Provided source code, scripts, design documents, and test reports |
---
## 13. Future Plans
The current project has completed the first-stage runnable prototype, and the next focus is:
1. Add resource-limited environment testing, such as 1 CPU/small memory scenarios;
3. Optimize `mcpd` forwarding path, such as connection reuse, thread pool, asynchronous I/O;
4. Strengthen OpenHarmony real-device or source tree compilation verification;
5. Prepare for the final competition PPT and 5-minute presentation video.
---
## 14. License
This project uses the MIT License, see:
```text
LICENSE
```
## 9. Agent Framework Access Instructions
Refer to `docs/agent_integration.md`. This document explains how to modify the upper-layer Agent framework, such as LangChain/HelloAgents, from directly connecting to MCP Server to connecting to the system `mcpd` and reusing system-level routing, caching, ACL, and progressive tool discovery capabilities.
### HMAC-SHA256 Signature Security Enhancement
`mcpd` supports optional request signature verification. After enabling `security.require_signature=true` in the configuration, the request must carry:
```text
X-Agent-Token: demo-token
X-Agent-Timestamp: 1710000000
X-MCP-Nonce: unique-nonce
X-Agent-Signature: sha256=<hmac_hex>
```
The signature message is:
```text
timestamp + "\n" + nonce + "\n" + raw_json_body
```
The signature algorithm is HMAC-SHA256. This mechanism is used to verify message integrity, anti-tampering, and combine nonce to prevent replay attacks.
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.