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
@registry.command
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)
# 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()
@registry.command
def get_discounted_price(price: float, discount: float = 0.0) -> float:
"""
Returns the price after applying a discount.
"""
return price * (1 - discount / 100)
# 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
License
MIT
Documentation
See docs/ for detailed guides, architecture, and examples.
📦 Примеры (examples/)
help_usage.py— базовое использование help-командыhelp_best_practices.py— best practices для helpproject_structure_example.py— структура проекта с MCPProxyAdapterdocstring_and_schema_example.py— как документировать команды для схемыtesting_example.py— как тестировать команды и интеграциюextension_example.py— как расширять и кастомизировать команды и help
✅ Чеклист для добавления новой команды
- Реализовать функцию-команду с подробным docstring (EN)
- Добавить описание параметров (type, description, required)
- Добавить описание возврата (docstring, тип)
- Зарегистрировать команду в registry/dispatcher
- Добавить описание в get_commands_info (использовать docstring)
- Покрыть тестами (unit/integration, edge-cases, ошибки)
- Добавить пример использования в examples/
- Проверить интеграцию с help (и с параметром, и без)
- Проверить генерацию схемы/OpenAPI
- Документировать в README.md (EN/RU)
📦 Examples (EN)
help_usage.py— basic help command usagehelp_best_practices.py— best practices for helpproject_structure_example.py— project structure with MCPProxyAdapterdocstring_and_schema_example.py— how to document commands for schematesting_example.py— how to test commands and integrationextension_example.py— how to extend/customize commands and help
✅ Checklist for adding a new command
- Implement the command function with detailed docstring (EN)
- Describe parameters (type, description, required)
- Describe return value (docstring, type)
- Register the command in registry/dispatcher
- Add description to get_commands_info (use docstring)
- Cover with tests (unit/integration, edge-cases, errors)
- Add usage example to examples/
- Check help integration (with/without param)
- Check schema/OpenAPI generation
- Document in README.md (EN/RU)
❓ FAQ
Ошибка: got multiple values for argument 'command' при вызове команды help
Проблема:
Если в JSON-RPC запросе к endpoint /cmd используется команда help с параметром command, может возникнуть ошибка:
TypeError: help_command() got multiple values for argument 'command'
Причина:
В Python, если метод execute(self, command, **params) получает параметр command и в params также есть ключ command, возникает конфликт имён.
Решение:
Переименуйте первый аргумент метода execute в классе MockDispatcher (и аналогичных) с command на command_name:
def execute(self, command_name, **params):
if command_name not in self.commands:
raise KeyError(f"Unknown command: {command_name}")
return self.commands[command_name](**params)
Это устранит конфликт и позволит корректно вызывать команду help с параметром command через JSON-RPC.
🚀 Deployment & Packaging FAQ
Как собрать, проверить и опубликовать пакет (wheel/sdist) с примерами и документацией
- Перенесите каталоги
examplesиdocsвнутрь основного пакета (например,mcp_proxy_adapter/examples,mcp_proxy_adapter/docs). - Обновите
setup.py:- Укажите
include_package_data=True. - В
package_dataдобавьте:package_data={ 'mcp_proxy_adapter': ['examples/*.py', 'examples/*.json', 'docs/*.md', '../README.md'], },
- Укажите
- Обновите
MANIFEST.in:- Убедитесь, что включены нужные файлы:
include README.md include LICENSE include requirements.txt include pyproject.toml include code_index.yaml recursive-include mcp_proxy_adapter/examples *.py *.json recursive-include mcp_proxy_adapter/docs *.md
- Убедитесь, что включены нужные файлы:
- Соберите пакет:
rm -rf dist build mcp_proxy_adapter.egg-info python3 -m build
- Создайте новое виртуальное окружение и установите пакет:
python3 -m venv ../mcp_proxy_adapter_test_env source ../mcp_proxy_adapter_test_env/bin/activate pip install --upgrade pip pip install dist/mcp_proxy_adapter-*.whl
- Проверьте, что примеры и документация попали в пакет:
ls -l ../mcp_proxy_adapter_test_env/lib/python*/site-packages/mcp_proxy_adapter/examples ls -l ../mcp_proxy_adapter_test_env/lib/python*/site-packages/mcp_proxy_adapter/docs
- Запустите пример сервера:
python ../mcp_proxy_adapter_test_env/lib/python*/site-packages/mcp_proxy_adapter/examples/openapi_server.py - Проверьте работоспособность через curl:
curl http://localhost:8000/openapi.json | jq .
- Публикация на PyPI:
- Проверьте, что у вас настроен
~/.pypircи установлен twine:pip install twine twine upload dist/*
- Проверьте, что у вас настроен
Типовые проблемы и решения
- Примеры или документация не попадают в пакет:
- Убедитесь, что они находятся внутри основного пакета и правильно указаны в
package_dataиMANIFEST.in.
- Убедитесь, что они находятся внутри основного пакета и правильно указаны в
- Каталог docs не виден в wheel:
- Проверьте расширения файлов и шаблоны в
package_data/MANIFEST.in.
- Проверьте расширения файлов и шаблоны в
- Проверяйте установку только через wheel, а не через sdist!
Best practice:
- Для публикации документации используйте GitHub и PyPI project page (README.md).
- Для примеров — всегда размещайте их внутри пакета, если хотите распространять с wheel.
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.10.tar.gz.
File metadata
- Download URL: mcp_proxy_adapter-2.1.10.tar.gz
- Upload date:
- Size: 64.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
29d3c44b95813d71f758d3be77bcb29bf504cf0647bf42b4aaa6ca18f8b81ef1
|
|
| MD5 |
b9f271c42cb29e9d15fcb08ff7115112
|
|
| BLAKE2b-256 |
9baad50c3b6f299571d7298cdcf95da81a5abc236627be47c161970dd4ed59aa
|
File details
Details for the file mcp_proxy_adapter-2.1.10-py3-none-any.whl.
File metadata
- Download URL: mcp_proxy_adapter-2.1.10-py3-none-any.whl
- Upload date:
- Size: 44.9 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 |
33d2af1d97f61dbbbaab3d25c8febbc57413692b9c3c505636829a75fe59646a
|
|
| MD5 |
d92d32790526874bf31c5a08fd7d647f
|
|
| BLAKE2b-256 |
63a3a52de3582cbdc6af197beeb4e6a4931b753ac54a519b9ee2aa75cc4f156b
|