Skip to main content
Glama
MCP Hackathon Server

MCP Hackathon Server

Official
by GSA-TTS

GSA MCP Hackathon — Шаблон сервера

Готовый стартовый набор для создания сервера Model Context Protocol (MCP) на Python, а также комплекты для развертывания на IBM Cloud (watsonx Orchestrate) и Databricks.

Создано с помощью FastMCP и uv. Если вы никогда не создавали MCP-сервер, начните с QUICKSTART.md.


Что такое MCP-сервер?

MCP-сервер предоставляет инструменты (функции, которые может вызывать модель), подсказки (многоразовые стартовые фразы для разговора) и ресурсы (данные, которые модель может читать) ИИ-клиенту, такому как Claude Desktop, Claude Code или агентной платформе, например watsonx Orchestrate. Вы пишете инструменты; модель клиента решает, когда их вызывать.

Этот шаблон дает вам работающий сервер с одним примером каждого типа, так что вы можете заменить примеры на свой собственный сервис и развернуть его.


Related MCP server: Python MCP Server Template

Структура репозитория

mcp-hackathon-template/
├── README.md                  # This file
├── QUICKSTART.md              # 5-minute clone → run → connect walkthrough
├── main.py                    # Local entry point (uv run python main.py)
├── pyproject.toml             # Package + dependencies (uv)
├── requirements.txt           # Mirror of runtime deps (for buildpack hosts)
├── Dockerfile                 # Container image (streamable-HTTP, port 8080)
├── manifest.yaml              # cloud.gov (Cloud Foundry) deploy
├── server.json                # MCP registry metadata
├── .env.example               # Copy to .env for local dev
├── .github/workflows/ci.yml   # Lint + test on push/PR
├── src/
│   └── example_server/        # ← rename to your service
│       ├── app.py             # Thin entry point: builds FastMCP, picks transport
│       ├── config.py          # Settings from env vars / .env
│       ├── models.py          # Pydantic models & enums for tool params
│       ├── utils.py           # Shared helpers (HTTP client, pagination)
│       ├── routes.py          # HTTP-only routes (/health, /version)
│       ├── tools/             # ONE FILE PER TOOL
│       │   ├── __init__.py    #   register_tools(mcp) aggregator
│       │   └── example_tool.py
│       ├── prompts/
│       │   ├── __init__.py    #   register_prompts(mcp) aggregator
│       │   └── example.py
│       └── resources/
│           ├── __init__.py    #   register_resources(mcp) aggregator
│           └── example.py
├── tests/                     # Import + registration smoke tests
├── eval/                      # Stub → build a Phoenix eval harness (see mcp-eval skill)
└── deploy/
    ├── README.md              # Which deployment kit to use
    ├── ibm/                   # watsonx Orchestrate: 3 kits (see below)
    └── databricks/            # Databricks Apps kit

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

Предварительные требования

  • uv — pip install uv или brew install uv

Установка и запуск

cp .env.example .env
uv sync
uv run python main.py

Сервер запускается в режиме stdio — он общается через JSON-RPC по stdin/stdout, именно так локальные клиенты (Claude Desktop, Claude Code) запускают его. См. QUICKSTART.md, чтобы подключить клиента.

Проверка

uv sync --group dev
uv run pytest tests/ -v      # tests
uv run ruff check .          # lint

Шаблон «один инструмент на файл»

Каждый инструмент находится в собственном файле в каталоге src/example_server/tools/ и предоставляет функцию register(mcp). tools/__init__.py вызывает каждый из них из единой функции register_tools(mcp). Это позволяет легко просматривать список инструментов и добавлять или удалять интеграцию, изменяя всего два файла.

Шаг 1 — создайте src/example_server/tools/my_tool.py:

from typing import Annotated
from fastmcp import FastMCP

from example_server.utils import fetch_json


def register(mcp: FastMCP) -> None:
    @mcp.tool(
        name="example_get_thing",
        annotations={
            "title": "Get a thing",
            "readOnlyHint": True,
            "destructiveHint": False,
            "idempotentHint": True,
            "openWorldHint": True,
        },
    )
    async def get_thing(thing_id: Annotated[str, "The ID to fetch."]) -> dict:
        """One-line summary. Document the data source, its update cadence,
        and the return shape here — the model reads this docstring."""
        return await fetch_json(f"https://api.example.gov/things/{thing_id}")

Шаг 2 — подключите его в tools/__init__.py:

from example_server.tools import example_tool, my_tool

def register_tools(mcp) -> None:
    example_tool.register(mcp)
    my_tool.register(mcp)  # ← add this line

Шаг 3 — добавьте любой API-ключ как типизированное поле в config.py и задокументируйте переменную окружения в .env.example.

Подсказки (prompts/) и ресурсы (resources/) следуют точно такому же шаблону register(mcp) + агрегатор.


Переименование пакета

Перед публикацией сервера переименуйте example_server в ваш сервис (например, census_mcp):

  1. Переименуйте папку src/example_server/ → src/<your_name>/.

  2. Обновите pyproject.toml: [project].name, [project.scripts] и [tool.hatch.build.targets.wheel].packages.

  3. Найдите и замените example_server во всех файлах src/, tests/, main.py, Dockerfile и manifest.yaml.


Советы по дизайну инструментов (федеральные данные)

  • Возвращайте структурированные данные, а не текст. Возвращайте словари/списки с согласованными ключами и позвольте модели описывать их.

  • Документируйте актуальность. Федеральные наборы данных отстают; укажите частоту обновления и дату "по состоянию на" в docstring.

  • Предоставляйте пагинацию. Используйте PaginationParams / paginate() из utils.py и возвращайте has_more / next_offset.

  • Используйте явные тайм-ауты. utils.fetch_json по умолчанию 30 секунд.

  • Полезные ошибки. Возвращайте словарь ошибок с hint, а не сырой стек вызовов.


Развертывание

Локальная разработка использует stdio. Чтобы поделиться сервером с агентной платформой, разверните его и зарегистрируйте. См. deploy/README.md для выбора варианта, затем:

  • IBM watsonx Orchestrate — deploy/ibm/ (три комплекта: локальный инструментарий stdio, Code Engine сборка из Git и готовый образ).

  • Databricks Apps — deploy/databricks/.

Оба используют один и тот же код сервера; app.py автоматически обслуживает HTTP, когда платформа предоставляет порт.


Оценка

Измерение того, насколько хорошо LLM может использовать ваши инструменты, — это настоящая проверка качества сервера. Этот шаблон намеренно не включает средство оценки — см. eval/README.md о том, как создать его с помощью навыка mcp-eval.


Лицензия

MIT. См. SECURITY.md о политике раскрытия уязвимостей и примечаниях по безопасности хакатона.

Available Tools

1 tool
example_search_datasetsSearch Datasets (example)B
Read-onlyIdempotent

Search federal datasets matching a query string. (STUB — replace me.)

This stub shows the shape of a real tool without calling a live API. Swap the body for an actual request using fetch_json(...); a worked pattern is included below in a comment.

Inputs: query (required), pagination, response_format. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.1/5.0

    Scored across 1 tool

    Disambiguation5/5

    Only one tool exists, so there is no possibility of confusion or overlap. The sole tool has a clear, singular purpose.

    Naming Consistency5/5

    With a single tool, there is no inconsistency in naming conventions. The name follows a verb_noun pattern (search_datasets).

    Tool Count1/5

    A single stub tool is a trivial surface for a server, far below the typical 3-15 tool range. It does not constitute a meaningful tool set.

    Completeness1/5

    The server is explicitly a stub with no real functionality, offering only a placeholder search. It has no coverage of any actual domain or workflow.

    Maintenance

    ActivityNo data
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      A basic MCP server template that provides a foundation for building custom tools, resources, and prompts. Serves as a starting point for developers to create their own MCP server functionality.
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      A foundational template for building MCP servers in Python using Streamable HTTP transport. Provides example implementations of tools, resources, and prompts to help developers create custom MCP integrations for AI assistants.
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      A minimal template MCP server demonstrating basic tools, resources, and prompts functionality. Includes example implementations like a hello tool, history resource, and greet prompt for learning MCP development.
      ISC