MyAIServ MCP Server
Servidor MCP - API de protocolo de contexto de modelo
MCP Server es una implementación basada en FastAPI del Protocolo de contexto de modelo (MCP) que proporciona una interfaz estandarizada para la interacción entre modelos LLM y aplicaciones.
Peculiaridades
🚀 API de alto rendimiento basada en FastAPI y operaciones asincrónicas
🔄 Soporte completo de MCP con recursos, instrumentos, indicaciones y muestreo
📊 Monitoreo y métricas a través de Prometheus y Grafana
🧩 Extensibilidad a través de interfaces sencillas para agregar nuevas herramientas
📝 API GraphQL para trabajar de forma flexible con datos
💬 Compatibilidad con WebSockets para interacción en tiempo real
🔍 Búsqueda semántica mediante integración con Elasticsearch
🗃️ Almacenamiento en caché a través de Redis para un mejor rendimiento
📦 Administre dependencias a través de Poetry para una gestión confiable de paquetes
Related MCP server: MCP Platform
Empezando
Instalación
Repositorio de clones:
git clone https://github.com/yourusername/myaiserv.git cd myaiservInstalar Poetry (si aún no está instalado):
curl -sSL https://install.python-poetry.org | python3 -Instalar dependencias mediante Poetry:
poetry install
Iniciando el servidor
poetry run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reloadO mediante la utilidad justa:
just runDespués del lanzamiento, la API estará disponible en: http://localhost:8000
Documentación de la API
Interfaz de usuario Swagger: http://localhost:8000/docs
ReDoc: http://localhost:8000/redoc
Zona de juegos de GraphQL: http://localhost:8000/graphql
Estructura del proyecto
myaiserv/
├── app/
│ ├── core/ # Базовые компоненты MCP
│ │ ├── base_mcp.py # Абстрактные классы MCP
│ │ └── base_sampling.py # Базовые классы для сэмплирования
│ ├── models/ # Pydantic модели
│ │ ├── mcp.py # Модели данных MCP
│ │ └── graphql.py # GraphQL схема
│ ├── services/ # Бизнес-логика
│ │ └── mcp_service.py # Сервис MCP
│ ├── storage/ # Хранилище данных
│ ├── tools/ # Инструменты MCP
│ │ ├── example_tool.py # Примеры инструментов
│ │ └── text_processor.py # Инструмент обработки текста
│ ├── utils/ # Утилиты
│ └── main.py # Точка входа FastAPI
├── app/tests/ # Тесты
├── docs/ # Документация
│ └── MCP_API.md # Описание API
├── pyproject.toml # Конфигурация Poetry и инструментов
└── .justfile # Задачи для утилиты justHerramientas disponibles
Herramienta del sistema de archivos
Una herramienta del sistema de archivos que admite la lectura, escritura, eliminación y listado de archivos.
curl -X POST "http://localhost:8000/tools/file_operations" \
-H "Content-Type: application/json" \
-d '{"operation": "list", "path": "."}'Herramienta meteorológica
Una herramienta para obtener datos meteorológicos por coordenadas.
curl -X POST "http://localhost:8000/tools/weather" \
-H "Content-Type: application/json" \
-d '{"latitude": 37.7749, "longitude": -122.4194}'Herramienta de análisis de texto
Una herramienta para el análisis de texto, que incluye detección de sentimientos y resumen.
curl -X POST "http://localhost:8000/tools/text_analysis" \
-H "Content-Type: application/json" \
-d '{"text": "Example text for analysis", "analysis_type": "sentiment"}'Herramienta de procesamiento de texto
Una herramienta para el procesamiento de texto, incluyendo formato, cálculo de estadísticas y extracción de entidades.
curl -X POST "http://localhost:8000/tools/text_processor" \
-H "Content-Type: application/json" \
-d '{"operation": "statistics", "text": "Example text", "stat_options": ["chars", "words"]}'Herramienta de procesamiento de imágenes
Una herramienta de procesamiento de imágenes que permite cambiar el tamaño, recortar y aplicar filtros.
curl -X POST "http://localhost:8000/tools/image_processing" \
-H "Content-Type: application/json" \
-d '{"operation": "resize", "image_data": "base64...", "params": {"width": 800, "height": 600}}'API de WebSocket
Para conectarse a la API de WebSocket:
const socket = new WebSocket("ws://localhost:8000/ws");
socket.onopen = () => {
socket.send(JSON.stringify({
type: "initialize",
id: "my-request-id"
}));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received:", data);
};API de GraphQL
Ejemplos de consultas mediante GraphQL:
# Получение списка всех инструментов
query {
getTools {
name
description
}
}
# Выполнение инструмента
mutation {
executeTool(input: {
name: "text_processor",
parameters: {
operation: "statistics",
text: "Example text for analysis"
}
}) {
content {
type
text
}
is_error
}
}Ejecución de pruebas
Para ejecutar pruebas, utiliza Poetry:
poetry run pytestO mediante la utilidad justa:
just testEstibador
Compilación y ejecución mediante Docker Compose
docker compose up -dPara iniciar servicios individuales:
docker compose up -d web redis elasticsearchIntegración con LLM
MCP Server proporciona una interfaz estandarizada para la integración con modelos LLM de varios proveedores:
import httpx
async def query_mcp_with_llm(prompt: str):
async with httpx.AsyncClient() as client:
# Запрос к MCP для получения контекста и инструментов
tools_response = await client.get("http://localhost:8000/tools")
tools = tools_response.json()["tools"]
# Отправка запроса к LLM с включением MCP контекста
llm_response = await client.post(
"https://api.example-llm.com/v1/chat",
json={
"messages": [
{"role": "system", "content": "You have access to the following tools:"},
{"role": "user", "content": prompt}
],
"tools": tools,
"tool_choice": "auto"
}
)
return llm_response.json()Métricas y seguimiento
El servidor MCP proporciona métricas en formato Prometheus a través del punto final /metrics . Las métricas incluyen:
Número de solicitudes a cada herramienta
Tiempo de ejecución de la consulta
Errores y excepciones
Desarrollo
Para formatear el código y comprobarlo con linters:
just fmt
just lintLicencia
This server cannot be deployed
Maintenance
Related MCP Connectors
Model Context Protocol server for the Apideck Unified API. Connect any MCP-compatible agent framework to 100+ accounting systems, HRIS platforms, file storage providers, and more through one integration. More information https://www.apideck.com/mcp-server
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
MCP server for building and testing AI agents with multi-model experimentation and insights.
Hosted MCP server for LLM cost estimation, model comparison, and budget-aware routing.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA high-performance Model Context Protocol (MCP) server designed for large language models, enabling real-time communication between AI models and applications with support for session management and intelligent tool registration.2MIT
- FlicenseNot gradedqualityNot gradedmaintenanceHigh-performance Model Context Protocol server supporting multiple LLM providers (OpenRouter, OpenAI, Groq) with WebSocket API and conversation history persistence.-
- FlicenseNot gradedqualityDmaintenanceA Model Context Protocol server implementation built with FastAPI that enables AI agent interactions. Provides a structured foundation for building AI-powered applications with proper data validation and modern Python tooling.-
- FlicenseNot gradedqualityNot gradedmaintenanceA production-ready Model Context Protocol server built with FastAPI, featuring JWT authentication, PostgreSQL database support, Redis caching, and comprehensive health monitoring for building secure async API applications.-