Adapter for exposing Command Registry commands as tools for AI models via MCP Proxy.
Project description
MCP Proxy Adapter
Adapter for integrating Command Registry with MCP Proxy, allowing you to use commands as tools for AI models.
Overview
MCP Proxy Adapter transforms commands registered in the Command Registry into a format compatible with MCP Proxy. This enables:
- Using existing commands as tools for AI models
- Creating a hybrid REST/JSON-RPC API for command execution
- Automatic generation of OpenAPI schemas optimized for MCP Proxy
- Managing tool metadata for better AI system integration
Installation
pip install mcp-proxy-adapter
Quick Start
from mcp_proxy_adapter import MCPProxyAdapter, CommandRegistry
from fastapi import FastAPI
# Create a command registry instance
registry = CommandRegistry()
# Register commands
def calculate_total(prices: list[float], discount: float = 0.0) -> float:
"""
Calculates the total price with discount.
Args:
prices: List of item prices
discount: Discount percentage (0-100)
Returns:
Total price with discount
"""
subtotal = sum(prices)
return subtotal * (1 - discount / 100)
registry.register_command("calculate_total", calculate_total)
# Create FastAPI app
app = FastAPI()
# Create and configure MCP Proxy adapter
adapter = MCPProxyAdapter(registry)
# Register endpoints in FastAPI app
adapter.register_endpoints(app)
# Generate and save MCP Proxy config
adapter.save_config_to_file("mcp_proxy_config.json")
Supported Request Formats
The adapter supports three request formats for command execution:
1. JSON-RPC format
{
"jsonrpc": "2.0",
"method": "command_name",
"params": {
"param1": "value1",
"param2": "value2"
},
"id": 1
}
Example request to /cmd endpoint:
curl -X POST -H "Content-Type: application/json" -d '{
"jsonrpc": "2.0",
"method": "calculate_total",
"params": {
"prices": [100, 200, 300],
"discount": 10
},
"id": 1
}' http://localhost:8000/cmd
Response:
{
"jsonrpc": "2.0",
"result": 540.0,
"id": 1
}
2. MCP Proxy format
{
"command": "command_name",
"params": {
"param1": "value1",
"param2": "value2"
}
}
Example request:
curl -X POST -H "Content-Type: application/json" -d '{
"command": "calculate_total",
"params": {
"prices": [100, 200, 300],
"discount": 10
}
}' http://localhost:8000/cmd
Response:
{
"result": 540.0
}
3. Params-only format
{
"params": {
"command": "command_name",
"param1": "value1",
"param2": "value2"
}
}
or
{
"params": {
"query": "command_name",
"param1": "value1",
"param2": "value2"
}
}
Example request:
curl -X POST -H "Content-Type: application/json" -d '{
"params": {
"command": "calculate_total",
"prices": [100, 200, 300],
"discount": 10
}
}' http://localhost:8000/cmd
Response:
{
"result": 540.0
}
Full Example: Integration with FastAPI
import logging
from fastapi import FastAPI, APIRouter
from mcp_proxy_adapter import CommandRegistry, MCPProxyAdapter, configure_logger
# Configure logging
logging.basicConfig(level=logging.INFO)
project_logger = logging.getLogger("my_project")
# Create FastAPI app
app = FastAPI(title="My API with MCP Proxy Integration")
# Create existing API router
router = APIRouter()
@router.get("/items")
async def get_items():
"""Returns a list of items."""
return [
{"id": 1, "name": "Smartphone X", "price": 999.99},
{"id": 2, "name": "Laptop Y", "price": 1499.99},
]
app.include_router(router)
# Register commands
registry = CommandRegistry()
def get_discounted_price(price: float, discount: float = 0.0) -> float:
"""
Returns the price after applying a discount.
"""
return price * (1 - discount / 100)
registry.register_command("get_discounted_price", get_discounted_price)
# Create and register MCP Proxy adapter
adapter = MCPProxyAdapter(registry)
adapter.register_endpoints(app)
# Save MCP Proxy config
adapter.save_config_to_file("mcp_proxy_config.json")
Features
- Universal JSON-RPC endpoint for command execution
- Automatic OpenAPI schema generation and optimization for MCP Proxy
- Tool metadata for AI models
- Customizable endpoints and logging
- Full test coverage and examples
FAQ
Q: Почему не удаётся использовать декоратор @registry.command для регистрации команд? A: В последних версиях пакета декоратор @registry.command больше не поддерживается. Теперь команды регистрируются только явно, через вызов метода:
registry.register_command("имя_команды", функция)
Q: Почему не удаётся импортировать CommandRegistry напрямую из mcp_proxy_adapter? A: Класс CommandRegistry находится в подмодуле registry. Используйте:
from mcp_proxy_adapter.registry import CommandRegistry
Q: Какой способ импорта MCPProxyAdapter и configure_logger? A: Импортируйте их из подмодуля adapter:
from mcp_proxy_adapter.adapter import MCPProxyAdapter, configure_logger
Q: Как добавить свою команду? A: Зарегистрируйте функцию через registry.register_command или декоратор (см. примеры выше).
Q: Как получить OpenAPI-схему? A: После регистрации адаптера вызовите /openapi.json в вашем FastAPI-приложении.
Q: Какой формат запроса поддерживается? A: JSON-RPC, MCP Proxy и params-only (см. раздел Supported Request Formats).
HOWTO
Как интегрировать MCP Proxy Adapter с FastAPI:
- Установите пакет:
pip install mcp-proxy-adapter
- Импортируйте нужные классы:
from mcp_proxy_adapter.registry import CommandRegistry from mcp_proxy_adapter.adapter import MCPProxyAdapter
- Зарегистрируйте команды и настройте FastAPI:
registry = CommandRegistry() registry.register_command("my_command", my_function) app = FastAPI() adapter = MCPProxyAdapter(registry) adapter.register_endpoints(app)
- (Опционально) Сохраните конфиг для MCP Proxy:
adapter.save_config_to_file("mcp_proxy_config.json")
Как добавить поддержку кастомного логгера:
import logging
from mcp_proxy_adapter.adapter import configure_logger
logger = logging.getLogger("my_project")
adapter_logger = configure_logger(logger)
Как получить список всех команд через API:
Вызовите GET /api/commands на вашем сервере FastAPI.
License
MIT
Documentation
See docs/ for detailed guides, architecture, and examples.
CI/CD & PyPI automation
This project uses GitHub Actions for continuous integration and automated publishing to PyPI.
- All tests are run on every push and pull request.
- On push of a new tag (vX.Y.Z), the package is built and published to PyPI automatically.
See .github/workflows/publish.yml for details.
Встроенная команда help: правила и типовые ошибки
Как работает
- Команда
helpвсегда встроена в MCPProxyAdapter и не требует реализации или регистрации со стороны пользователя. - Для получения справки по конкретной команде используйте параметр
cmdname:{"jsonrpc": "2.0", "method": "help", "params": {"cmdname": "имя_команды"}, "id": 1}
- Для получения списка всех команд:
{"jsonrpc": "2.0", "method": "help", "id": 1}
Типовые ошибки и их решения
- Ошибка: передан параметр
commandвместоcmdname- Ответ:
{"error": "Parameter 'command' is not supported. Use 'cmdname' instead.", "hint": "Send params: {\"cmdname\": \"your_command\"}", ...}
- Решение: всегда используйте
cmdname.
- Ответ:
- Ошибка сериализации coroutine
- Причина: handler вызывается без await, либо возвращает coroutine.
- Ответ:
{"error": "Help handler must be awaited. Call as await dispatcher.execute('help', ...) in async context.", ...}
- Решение: всегда await-ить dispatcher.execute в async endpoint.
Важно для интеграторов и пользователей
- Не реализуйте свой обработчик help — используйте встроенный.
- Не используйте параметр
command— толькоcmdname. - Все ошибки help-команды теперь сопровождаются понятной подсказкой и примером корректного запроса.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mcp_proxy_adapter-2.1.17.tar.gz.
File metadata
- Download URL: mcp_proxy_adapter-2.1.17.tar.gz
- Upload date:
- Size: 66.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cfa0d1e8eee75b938715e7446ef4ca33de5efe7a910c54373856da19ebdf1fec
|
|
| MD5 |
7e4d06701478531de73c7785d96d3490
|
|
| BLAKE2b-256 |
b53985a7c29fb1001bba39a2e464e85edf66a1928c675042f42037bffa9b1d18
|
File details
Details for the file mcp_proxy_adapter-2.1.17-py3-none-any.whl.
File metadata
- Download URL: mcp_proxy_adapter-2.1.17-py3-none-any.whl
- Upload date:
- Size: 45.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a373f7972dd7fffd4a22e8cda499ba5215a842e619f4ce55e5c6ca4802d0644f
|
|
| MD5 |
b70d7184fc9733f127d1a05ea0e96c2b
|
|
| BLAKE2b-256 |
a6014a88c718ddb897138547a3f7820f766935e2e5056b5ccecafefe3c4a9330
|