Skip to main content
Glama

Local Coder MCP Agent

Этот проект собирает локальный рабочий процесс кодинг-агента:

  1. Кодинг-модель Qwen работает локально через OpenAI-совместимый API /v1/chat/completions.

  2. Python-воркер общается с этим локальным API через OpenAI SDK.

  3. MCP-сервер local-coder предоставляет Codex функцию delegate_to_local_coder.

  4. Codex делегирует задачи по реализации локальному воркеру, а затем сам проверяет тесты и диффы.

Веса моделей не включены. Используйте собственную локальную директорию модели через MODEL_DIR.

Архитектура

Codex
  -> MCP tool: delegate_to_local_coder(task, workspace, max_steps)
    -> mcp_servers.local_coder.server
      -> workers.coding.worker.CodingWorker
        -> OpenAI-compatible local model server
        -> restricted file/test/git tools inside the requested workspace

Воркер умеет выводить список файлов, читать файлы, записывать файлы, вносить точечные правки по точному тексту, запускать pytest, выполнять небольшой список разрешённых команд, искать текст, просматривать git status и git diff. Он отклоняет пути за пределами выбранного рабочего пространства.

Related MCP server: Codex Workspace Bridge

Установка

git clone <your-repo-url>
cd local-coder-mcp-agent
python -m venv .venv
source .venv/bin/activate
python -m pip install -U pip
python -m pip install -e ".[dev,mlx]"
cp .env.example .env

Отредактируйте .env:

MODEL_DIR=${HOME}/models/Qwen3-Coder-30B-A3B-Instruct-4bit
ALLOWED_WORKSPACE_ROOT=${HOME}/AI/projects
LOCAL_CODER_BASE_URL=http://127.0.0.1:8080/v1
LOCAL_CODER_MODEL=default_model
LOCAL_CODER_API_KEY=local

ALLOWED_WORKSPACE_ROOL — это дерево дирректорий, которое воркер можно редактировать. Длу корневый корнеей используйте ALLOWED_WORKSPACE_ROOOTS, разделзуя их : на macOS/Linux.

Запуск сервера модели

Длуя MLX-модели на Apple Silicone:

source .venv/bin/activate
./scripts/start_qwen3_coder_server.sh

Скрипт запускает:

python -m mlx_lm.server \
  --model "${MODEL_DIR}" \
  --host 127.0.0.1 \
  --port 8080 \
  --max-tokens 4096 \
  --temp 0

Подойдёт любой сервер, совместиый с OpenAI, если он предоставляет http://127.0.0.1:8080/v1/chat/completions, или если вы обновите LOCAL_CODER_BASE_URL.

Запуск MCP-сервера вручную

source .venv/bin/activate
./scripts/start_local_coder_mcp.sh

Обычно Codex сам запускает MCP-сервер из config_toml.

Настройка MCP для Codex

Скопируйте блок local-coder из config.example.toml в свой Codex config.toml, затем замените плейсHoldеры локальными значениями:

[mcp_servers.local-coder]
enabled = true
command = "${PROJECT_ROOT}/.venv/bin/python"
args = ["-m", "mcp_servers.local_coder.server"]
cwd = "${PROJECT_ROOT}"

[mcp_servers.local-coder.env]
LOCAL_CODER_BASE_URL = "http://127.0.0.1:8080/v1"
LOCAL_CODER_MODEL = "default_model"
LOCAL_CODER_API_KEY = "local"
ALLOWED_WORKSPACE_ROOT = "${ALLOWED_WORKSPACE_ROOT}"

Используйте реальные локальные пути только в вашем приватном конфиге Codex, никому не передавайте.

Делегирование задачи из Codex

Пример промпта для Codex:

Use the local-coder MCP server and specifically call delegate_to_local_coder.

Workspace:
${ALLOWED_WORKSPACE_ROOT}/sandbox

Task:
Add multiply(a: int, b: int) -> int to calculator.py.

Requirements:
- Do not change add(), subtract(), or divide().
- Add pytest coverage for multiply().
- Run all tests.
- Inspect git diff before finishing.

After the local worker completes the task, review its changes yourself.
Do not implement the change yourself unless the local worker fails.

В состав включена папка examples/sandbox — небольшой pytest-проект для сmoкевых тестов.

Распространённые ошибки

Рабочее пространство не находится внутри разрешённого корня

Установите ALLOWED_WORKSPACE_ROOT или ALLOWED_WORKSPACE_ROOTS, чтобы запрошенное рабочее пространство находилось внутри разрешённой директории. Это сделано намеренно: воркеру не должно быть разрешено редактировать произвольные локальные файлы.

Воркер превысил лимит количества шагов

Увеличьте max_steps для более крупных задач или разбейте задачу на более мелкие шаги. Хорошие задачи для локального воркера — конкретные и проverяемые.

Модель вернула нет текста

Локальный сервер модели вернул ответ без полезного content, reasoning_content, reasoning или thinking. Попробуйте:

  • Убедитесь, что сервер реализует OpenAI-совместимые chat completions.

  • Укажите LOCAL_CODER_ENABLE_THINKING=false.

  • Уменьшите размер задачи.

  • Простестируйте сервер прямым запросом /v1/chat/completions.

Сбой соединения

Убедитесь, что сервер модели запущен, порт совпадает с LOCAL_CODER_BASE_URL и никакой брандмауэр или прокси не перехватывает трафик localhost.

Примечания по безопасности

  • Не коммитьте .env, приватный конфиг Codex, веса моделей, логи, ключи или сгенерированные кэши.

  • Держите ALLOWED_WORKSPACE_ROOT узким.

  • Локальный работник может редактировать и выполнять ограниченные команды внутри разрешённых рабочих пространств; проверяйте каждый diff перед применением изменений.

  • Держите API-server привязанным к локальному 127.0.0.1, если у вас нет отдельного плана сетевого обеспечения.

  • В этом репозитории намеренно используются плейсхолдеры, такие как ${HOME}, ${MODEL_DIR}, ${PROJECT_ROOT} и ${ALLOWED_WORKSPACE_ROOT}.

Запуск проверок

python -m pytest -q
python -m py_compile \
  mcp_servers/local_coder/server.py \
  workers/coding/client.py \
  workers/coding/parser.py \
  workers/coding/tools.py \
  workers/coding/worker.py

Available Tools

1 tool
delegate_to_local_coderB

Delegate a coding implementation task to the local Qwen worker.

The worker can inspect project files, patch code, create files, run tests, and inspect git diff. Codex should review the result afterwards.

NameRequiredDescriptionDefault
taskYes
max_stepsNo
workspaceYes

Output Schema

NameRequiredDescription
resultYes

TDQS

B3.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden of behavioral disclosure. It states the worker can inspect files, patch code, create files, run tests, and inspect git diff, which clearly indicates a mutation of the workspace. It also suggests a follow-up review by Codex. This covers primary side effects but omits details like async behavior, failure modes, or timeouts, which are not disclosed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loading the purpose and then listing capabilities and a workflow note. There is zero fluff, and every sentence contributes meaning. It is appropriately sized for a tool of moderate complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

While the output schema exists and could describe return values, the description omits essential parameter semantics, making it incomplete for correct invocation. It also lacks preconditions (e.g., workspace must be a local path) and any error/edge-case context. For a delegation tool, the agent needs to know how to construct the task and workspace.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema has 0% description coverage, so the description must explain parameter meanings. It does not mention 'task', 'workspace', or 'max_steps' at all. An agent cannot infer what constitutes a valid 'workspace' (e.g., path, repo URL) or what 'max_steps' controls. This is a critical omission.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool delegates a coding implementation task to a local Qwen worker, using the verb 'delegate' with a specific resource. It also lists the worker's capabilities, which distinguishes what the tool can do. However, it could be more explicit about the scope of 'implementation' (e.g., only code changes vs. tests), though it is not misleading.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies when to use it (for coding implementation tasks) but does not provide explicit guidance on when not to use it or alternatives. There are no sibling tools, so differentiation is not needed, but the description lacks conditions or prerequisites such as workspace requirements. The note to 'review the result afterwards' gives a follow-up action but not selection criteria.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

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

  1. 1 tool updatev0.1.0
    • First observeddelegate_to_local_coder

TDQS

B3.4/5.0

Scored across 1 tool

Disambiguation5/5

There is only one tool, so there are no overlapping purposes or risk of selecting the wrong tool. The tool's purpose is clearly stated and unique within this server.

Naming Consistency5/5

The single tool name uses a clear, descriptive verb-target structure: delegate_to_local_coder. With no other tools to conflict with, there is no naming inconsistency.

Tool Count2/5

A single tool feels too thin for the broad local-coding scope described, which includes inspecting files, patching code, creating files, running tests, and checking diffs. The entire capability set is buried behind one opaque delegation endpoint.

Completeness3/5

The delegate tool covers task handoff and appears to return results for review, but there are no separate tools for status, cancellation, or finer-grained control of coding operations. This makes the surface usable for simple flows but incomplete for managing the full lifecycle of delegated work.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    A
    maintenance
    Enables ChatGPT to operate authorized local projects through MCP, including reading and modifying code, viewing Git changes, running configured programs, and reading local Codex sessions to continue work.
    53 npm
    7
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables Codex to delegate scoped coding tasks to DeepSeek Harness subagents over MCP using the official ACP, then wait for results, resume the same session with corrections, and forward permission requests. Read-only and workspace-write modes let results be reviewed and independently verified before acceptance.
    MIT