I craft unique cereal names, stories, and ridiculously cute Cereal Baby images.

myaiserv
High-performance FastAPI server implementing Model Context Protocol (MCP) for seamless integration with Large Language Models (LLMs). Built with modern stack: FastAPI, Elasticsearch, Redis, Prometheus, and Grafana.
1
Github Watches
6
Github Forks
9
Github Stars
MCP Server - Model Context Protocol API
MCP Server - это реализация Model Context Protocol (MCP) на базе FastAPI, предоставляющая стандартизированный интерфейс для взаимодействия между LLM-моделями и приложениями.
Особенности
- 🚀 Высокопроизводительный API на базе FastAPI и асинхронных операций
- 🔄 Полная поддержка MCP с ресурсами, инструментами, промптами и сэмплированием
- 📊 Мониторинг и метрики через Prometheus и Grafana
- 🧩 Расширяемость через простые интерфейсы для добавления новых инструментов
- 📝 GraphQL API для гибкой работы с данными
- 💬 WebSocket поддержка для реал-тайм взаимодействия
- 🔍 Семантический поиск через интеграцию с Elasticsearch
- 🗃️ Кэширование через Redis для улучшения производительности
- 📦 Управление зависимостями через Poetry для надежного управления пакетами
Начало работы
Установка
-
Клонировать репозиторий:
git clone https://github.com/yourusername/myaiserv.git cd myaiserv
-
Установить Poetry (если еще не установлен):
curl -sSL https://install.python-poetry.org | python3 -
-
Установить зависимости через Poetry:
poetry install
Запуск сервера
poetry run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
Или через утилиту just:
just run
После запуска API доступен по адресу: http://localhost:8000
Документация API
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- GraphQL Playground: http://localhost:8000/graphql
Структура проекта
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 # Задачи для утилиты just
Доступные инструменты
File System Tool
Инструмент для работы с файловой системой, поддерживающий операции чтения, записи, удаления и листинга файлов.
curl -X POST "http://localhost:8000/tools/file_operations" \
-H "Content-Type: application/json" \
-d '{"operation": "list", "path": "."}'
Weather Tool
Инструмент для получения погодных данных по координатам.
curl -X POST "http://localhost:8000/tools/weather" \
-H "Content-Type: application/json" \
-d '{"latitude": 37.7749, "longitude": -122.4194}'
Text Analysis Tool
Инструмент для анализа текста, включая определение тональности и суммаризацию.
curl -X POST "http://localhost:8000/tools/text_analysis" \
-H "Content-Type: application/json" \
-d '{"text": "Example text for analysis", "analysis_type": "sentiment"}'
Text Processor Tool
Инструмент для обработки текста, включая форматирование, расчет статистики, извлечение сущностей.
curl -X POST "http://localhost:8000/tools/text_processor" \
-H "Content-Type: application/json" \
-d '{"operation": "statistics", "text": "Example text", "stat_options": ["chars", "words"]}'
Image Processing Tool
Инструмент для обработки изображений, поддерживающий изменение размера, обрезку и применение фильтров.
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}}'
WebSocket API
Для подключения к WebSocket API:
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);
};
GraphQL API
Примеры запросов через GraphQL:
# Получение списка всех инструментов
query {
getTools {
name
description
}
}
# Выполнение инструмента
mutation {
executeTool(input: {
name: "text_processor",
parameters: {
operation: "statistics",
text: "Example text for analysis"
}
}) {
content {
type
text
}
is_error
}
}
Запуск тестов
Для запуска тестов используйте Poetry:
poetry run pytest
Или через утилиту just:
just test
Docker
Сборка и запуск через Docker Compose
docker compose up -d
Для запуска отдельных сервисов:
docker compose up -d web redis elasticsearch
Интеграция с LLM
MCP Server предоставляет стандартизированный интерфейс для интеграции с LLM-моделями различных поставщиков:
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()
Метрики и мониторинг
MCP Server предоставляет метрики в формате Prometheus по эндпоинту /metrics
. Метрики включают:
- Количество запросов к каждому инструменту
- Время выполнения запросов
- Ошибки и исключения
Разработка
Для форматирования кода и проверки линтерами:
just fmt
just lint
Лицензия
相关推荐
I find academic articles and books for research and literature reviews.
Evaluator for marketplace product descriptions, checks for relevancy and keyword stuffing.
Confidential guide on numerology and astrology, based of GG33 Public information
Emulating Dr. Jordan B. Peterson's style in providing life advice and insights.
Your go-to expert in the Rust ecosystem, specializing in precise code interpretation, up-to-date crate version checking, and in-depth source code analysis. I offer accurate, context-aware insights for all your Rust programming questions.
This GPT assists in finding a top-rated business CPA - local or virtual. We account for their qualifications, experience, testimonials and reviews. Business operators provide a short description of your business, services wanted, and city or state.
Advanced software engineer GPT that excels through nailing the basics.
Converts Figma frames into front-end code for various mobile frameworks.
Discover the most comprehensive and up-to-date collection of MCP servers in the market. This repository serves as a centralized hub, offering an extensive catalog of open-source and proprietary MCP servers, complete with features, documentation links, and contributors.
The all-in-one Desktop & Docker AI application with built-in RAG, AI agents, No-code agent builder, MCP compatibility, and more.
Micropython I2C-based manipulation of the MCP series GPIO expander, derived from Adafruit_MCP230xx
Fair-code workflow automation platform with native AI capabilities. Combine visual building with custom code, self-host or cloud, 400+ integrations.
Mirror ofhttps://github.com/agentience/practices_mcp_server
🧑🚀 全世界最好的LLM资料总结(Agent框架、辅助编程、数据处理、模型训练、模型推理、o1 模型、MCP、小语言模型、视觉语言模型) | Summary of the world's best LLM resources.
Reviews

user_9sC7YZ3s
I've been using MCP Tools Project for a while now, and it has exceeded my expectations. The automation capabilities are fantastic, and it has significantly streamlined my workflow. Kudos to djpapzin for creating such a robust tool. Highly recommended for anyone looking to enhance their productivity.