Skip to main content
Glama

MyAIServ MCP Server

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 для надежного управления пакетами

Начало работы

Установка

  1. Клонировать репозиторий:
    git clone https://github.com/yourusername/myaiserv.git cd myaiserv
  2. Установить Poetry (если еще не установлен):
    curl -sSL https://install.python-poetry.org | python3 -
  3. Установить зависимости через 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

Структура проекта

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

Лицензия

MIT License

-
security - not tested
A
license - permissive license
-
quality - not tested

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

A high-performance FastAPI server supporting Model Context Protocol (MCP) for seamless integration with Large Language Models, featuring REST, GraphQL, and WebSocket APIs, along with real-time monitoring and vector search capabilities.

  1. Peculiarities
    1. Getting Started
      1. Installation
      2. Starting the server
      3. API Documentation
    2. Project structure
      1. Available tools
        1. File System Tool
        2. Weather Tool
        3. Text Analysis Tool
        4. Text Processor Tool
        5. Image Processing Tool
      2. WebSocket API
        1. GraphQL API
          1. Running tests
            1. Docker
              1. Building and running via Docker Compose
            2. Integration with LLM
              1. Metrics and monitoring
                1. Development
                  1. License

                    Related MCP Servers

                    • -
                      security
                      F
                      license
                      -
                      quality
                      A production-ready MCP server built with FastAPI, providing an enhanced tool registry for creating, managing, and documenting AI tools for Large Language Models (LLMs).
                      Last updated -
                      33
                    • -
                      security
                      A
                      license
                      -
                      quality
                      A Model Context Protocol (MCP) compliant server that allows Large Language Models (LLMs) to search and retrieve content from microCMS APIs.
                      Last updated -
                      MIT License
                    • -
                      security
                      A
                      license
                      -
                      quality
                      A 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.
                      Last updated -
                      2
                      MIT License
                    • -
                      security
                      F
                      license
                      -
                      quality
                      A FastAPI server implementing the Model Context Protocol (MCP) for structured tool use, providing utility tools including random number generation, image generation via Azure OpenAI DALL-E, and AI podcast generation.
                      Last updated -

                    View all related MCP servers

                    MCP directory API

                    We provide all the information about MCP servers via our MCP API.

                    curl -X GET 'https://glama.ai/api/mcp/v1/servers/eagurin/myaiserv'

                    If you have feedback or need assistance with the MCP directory API, please join our Discord server