Skip to main content

Design Specification: Go-Based Model Context Protocol (MCP) Server for GitHub Backup & Observatory System

Document Version: 1.0.0
Status: DRAFT / PROPOSED
Author: MishraShardendu22
Target Clients: Claude Desktop, Claude Code, OpenAI Codex and any other MCP client
Implementation Language: Go 1.26+


1. Executive Summary & Objectives​

The GitHub Backup Automation & Observatory System currently features a rich ecosystem of tools distributed across its Go Backend API, Python AI Observatory, and Go Backup Worker:

  • Real-time backup telemetry and historical analytics snapshots.
  • Repository tracking, size trends, and commit verification.
  • Detailed execution logs with multi-level filtering.
  • Hybrid vector search (pgvector + PostgreSQL Full-Text Search).
  • Incident fix registration and tracking (backup_fixes).
  • Archive management: git bundles and legacy tarballs.

Currently, these tools are consumed either via the Next.js Web Dashboard or internally by the LangChain agent in the Python Observatory.

Core Objective​

This design document specifies the architecture, tool schemas, transport mechanisms, and integration patterns for building a dedicated, high-performance Go MCP Server (github-backup-mcp).

By exposing these capabilities via the open Model Context Protocol (MCP), external AI coding agents, such as Anthropic Claude (Claude Desktop and Claude Code) and OpenAI Codex, can directly connect to the backup infrastructure to:

  1. Inspect & Observe: Monitor real-time backup health, review run histories, and inspect archive growth without opening a browser.
  2. Diagnose & Correlate: Automatically triage clone failures, rate-limit lockouts, or network timeouts by aggregating run results, execution logs, and semantic past-incident memory in a single reasoning step.
  3. Fix & Remediate: Propose, apply, and permanently record incident fixes (backup_fixes) with linked commit hashes and affected run IDs.
  4. Operate & Restore: Verify archive checksums, inspect files within compressed .tar.gz snapshots without full extraction, and trigger on-demand backup runs for specific repositories.

2. Why Go for the MCP Server?​

While MCP servers can be written in TypeScript or Python, building this server in Go provides decisive engineering advantages:

DimensionGo ImplementationPython / Node Alternatives
Binary FootprintSingle static executable (~15MB), zero external runtime dependenciesRequires Python 3.12 + venv or Node.js + node_modules
Startup LatencyInstantaneous cold start (<15ms) via stdio pipe300ms - 1500ms interpreter initialization overhead
Memory Footprint~12MB RSS idle / ~25MB peak80MB - 200MB RSS idle
Codebase SynergyShares the platform's Go packages (auth, svcauth, tenancy, logging, portset) with the APIRequires duplicate data contract definitions and serialization logic
Concurrency ModelNative lightweight goroutines for async log tailing, health checks, and concurrent tool callsEvent-loop / thread-pool management complexity
Transport VersatilityEffortlessly supports both stdio (local IDE pipe) and SSE/HTTP (remote cloud daemon) in a single binaryFrequently requires separate framework stacks

3. System Architecture & Component Interactions​

graph TD
subgraph AI Client Layer
Claude[Claude Desktop / Claude Code]
Codex[OpenAI Codex CLI]
Other[Other MCP Clients]
end

subgraph MCP Transport Boundary
StdioTransport[Stdio Transport - Local Process Pipe]
SSETransport[SSE / HTTP Transport - Port 8090]
end

Claude -->|JSON-RPC 2.0 via Stdio| StdioTransport
Codex -->|JSON-RPC 2.0 via Stdio| StdioTransport
Other -->|JSON-RPC 2.0 via Stdio or HTTP| StdioTransport

subgraph Go MCP Server Subsystem [github-backup-mcp]
Router[MCP Dispatcher & Protocol Engine - mark3labs/mcp-go]
Sanitizer[Security Filter & Secret Redactor]

subgraph Handlers
ObsHandler[Observability & Telemetry Tools]
DiagHandler[Diagnostic & Failure Triaging Tools]
ArchiveHandler[Archive Inspection & Integrity Tools]
FixHandler[Remediation & Fix Recording Tools]
SearchHandler[Hybrid Search & Knowledge Tools]
end

Router --> Sanitizer
Sanitizer --> ObsHandler
Sanitizer --> DiagHandler
Sanitizer --> ArchiveHandler
Sanitizer --> FixHandler
Sanitizer --> SearchHandler
end

StdioTransport --> Router
SSETransport --> Router

subgraph Backend Infrastructure
GoBackend[Go Backend REST API :8080]
PythonObs[Python AI Observatory :8000]
LocalArchives[Local Archive Storage _Repos/ & Backups]
end

ObsHandler -->|HTTP| GoBackend
DiagHandler -->|HTTP| GoBackend
FixHandler -->|HTTP POST /api/requests, /api/fixes| GoBackend
ArchiveHandler -->|Direct File I/O & SHA-256| LocalArchives
ArchiveHandler -->|HTTP recorded archive| GoBackend
SearchHandler -->|HTTP POST /search| PythonObs

Architectural Highlights:​

  1. Data access through the backup API: the server has no database. Every tool and resource reads and writes through the Go Backend REST API (BACKEND_URL: http://localhost:8080, or Caddy's internal listener http://caddy:8080 on a self-hosted machine; one URL for identity, runs and insights), through one typed client (tools/apiclient.go), for the caller's account: with the caller's own personal access token as the bearer, and for the owner without one (stdio, MCP_AUTH_TOKEN) with the server's own credential SERVICE_CREDENTIAL plus X-Account-Id: 1. Without SERVICE_CREDENTIAL it calls with the deprecated INTERNAL_SECRET plus X-Account-Id: <account> for every caller (see 8.2). A non-2xx answer is a tool error naming the status, the API's error code and message, its wait for a 429 and its request id. Every request carries the MCP request's X-Request-ID (the client's own when valid, else a new one per tool call); the two writes carry an Idempotency-Key and are retried once after a transport error or a 5xx. The tools map the API's answers to the outputs documented below. DATABASE_URL is ignored (a startup warning; its password is still redacted for one release).
  2. Secret Redaction Layer: A tool handler middleware passes every tool result, errors included, through the sanitizer (see 8.3), for every transport.
  3. Transports (--transport or MCP_TRANSPORT):
    • stdio: Default mode when spawned directly by Claude Desktop, Claude Code or Codex. Logs go to stderr only.
    • http: Streamable HTTP at /mcp on MCP_PORT or --port (default 8090; it never reads PORT/SERVER_PORT, which belong to the API), stateless (no session ID, nothing kept in memory between requests), with a public GET /health. Use this for containers, several replicas and remote access.
    • sse: The legacy SSE transport (/sse + /message). Its sessions live in one process's memory, so it only works with a single instance; prefer http.
  4. Logging: slog JSON through src/platform/logging (service github-backup-mcp, LOG_LEVEL), always on stderr, with one record per MCP request and per tool call (names, durations and outcomes, never arguments or tokens).
  5. Accounts: every request runs for one account, the principal of its credential (8.2). Every API call a tool or resource makes acts for that account, and the API filters by it, so a caller sees and changes only its own runs, results, logs, fixes and requests; an id of another account answers exactly like an id that does not exist.

4. MCP Tools Specification​

The server exposes 14 tools in 5 groups. The tool definitions in src/backend/github-backup-mcp/tools/*.go are the source of truth for names and parameters. Every tool answers for the caller's account only (3, item 5); the two remediation tools need the write scope and the archive tools serve the owner's account only (8.1, 8.2):

github-backup-mcp
├── 1. Observability & Telemetry (Read-only)
│ ├── get_system_health
│ ├── get_dashboard_summary
│ ├── get_backup_metrics
│ └── list_tracked_repositories
├── 2. Diagnostics & Failure Triaging (Read-only)
│ ├── list_backup_runs
│ ├── get_backup_run_details
│ ├── get_execution_logs
│ └── diagnose_backup_failure
├── 3. Semantic Search & Memory (Read-only)
│ └── search_backup_knowledge
├── 4. Archive & File Inspection (Read-only / Safe Sandbox)
│ ├── verify_archive_integrity
│ ├── inspect_archive_contents
│ └── extract_backup_file
└── 5. Remediation & Operations (State-Modifying / HITL-Gated)
├── trigger_backup_run
└── record_backup_fix

Category 1: Observability & Telemetry​

1. get_system_health​

  • Description: Asks the backup API's public readiness route (GET /readyz, no credential), which reports whether the API's PostgreSQL database answers, and checks the archive directory's disk on this host. status is HEALTHY when the API is ready, DEGRADED when it answers but its database does not (database.status = "error", database.state the API's word, such as disconnected), and UNHEALTHY when the API cannot be reached (database.status = "unknown"). The deployment's own details (archive storage on the MCP host, the API's URL and error messages) are shown to the owner's account only; other accounts see each component's status and storage.status = "not_applicable". The server has no database connection of its own, so pool statistics are no longer reported.
  • Parameters: None.
  • Output:
    {
    "status": "HEALTHY",
    "database": {"status": "connected", "source": "backup API (GET /readyz)"},
    "storage": {"status": "accessible", "path": "_Repos", "total_disk_bytes": 107374182400, "available_disk_bytes": 68719476736},
    "backend_api": {"status": "healthy", "http_status": 200, "latency_ms": 14, "url": "http://localhost:8080"}
    }

2. get_dashboard_summary​

  • Description: Retrieves high-level aggregated metrics across all backup history: total runs, overall success rate, distinct repos, total archive size, and latest execution status. The numbers are the API's dashboard's own (getDashboardStats), so the dashboard and the tool cannot disagree: success_rate is 100 - failed / total_repos * 100 (skipped repositories do not count as failed), formatted here with two decimals, and the totals from results (distinct repositories, archive sizes, the largest repository) count a run's results once it ended.
  • Parameters: None.
  • Output:
    {
    "total_runs": 150,
    "total_repos_processed": 1250,
    "total_successful": 1180,
    "total_failed": 45,
    "total_skipped": 25,
    "distinct_repositories": 48,
    "success_rate": "94.40%",
    "last_run_status": "completed",
    "last_run_at": "2026-09-18T10:45:30Z",
    "avg_duration_ms": 870000,
    "total_backup_size_bytes": 536870912,
    "largest_archive_bytes": 104857600,
    "largest_repository": "MishraShardendu22/large-repo"
    }

3. get_backup_metrics​

  • Description: Returns historical time-series metrics over a specified number of days, including daily run counts, success rates, and average duration. The runs come from the API's getRunMetrics?days= and are grouped here by the UTC day they started, newest day first; a day's avg_duration_ms averages its ended runs. The API lists at most the newest 1,000 runs of the window; runs_truncated says when it left some out.
  • Parameters:
    • days (integer, optional, default: 30, at most 365): Days of history to analyze.
    • limit (integer, optional, default: 50): Maximum number of days returned.
  • Output:
    {
    "period_days": 30,
    "data_points": 1,
    "history": [
    {"date": "2026-09-17", "run_count": 1, "successful": 42, "failed": 2, "skipped": 0, "avg_duration_ms": 850000}
    ],
    "runs_truncated": false
    }

4. list_tracked_repositories​

  • Description: Lists tracked GitHub repositories with their newest result (the API's listRepositories): repo_full_name, last_status, last_commit_hash, archive_size_bytes and last_backed_up, with total_tracked, page and limit.
  • Parameters:
    • page (integer, optional, default: 1)
    • limit (integer, optional, default: 50, max: 200)

Category 2: Diagnostics & Failure Triaging​

5. list_backup_runs​

  • Description: Retrieves paginated backup runs, optionally filtered by status (completed, failed, running).
  • Parameters:
    • page (integer, optional, default: 1)
    • limit (integer, optional, default: 20, max: 100)
    • status (string, optional): completed, failed or running, sent to the API's listBackupRuns?status=. An older API ignores it; the tool filters the page again, so it may be short but holds no other status.

6. get_backup_run_details​

  • Description: Retrieves complete execution details of a specific backup run (the API's getBackupRun), including all individual repository outcomes, durations, commit hashes, and error messages; failures first, then the largest archives. A run of another account is "not found".
  • Parameters:
    • run_id (integer, required): The unique ID of the backup run.

7. get_execution_logs​

  • Description: Queries stored operational logs with filtering by severity level, backup run ID, or target repository.
  • Parameters:
    • run_id (integer, optional): Filter by backup run.
    • repository (string, optional): Filter by repository full name (e.g. owner/repo, any case), sent to the API's listExecutionLogs?repository=. An older API ignores it; the tool filters again.
    • level (string, optional): One of INFO, WARN, ERROR, DEBUG (case-insensitive); omit it for every level.
    • limit (integer, optional, default: 50, max: 200).

8. diagnose_backup_failure​

  • Description: Compound Diagnostic Tool. Given a run_id (or defaulting to the latest failed run), this tool collects the failed repositories with their errors and error logs, attaches the three newest recorded fixes, and returns one diagnostic packet for the LLM. For similar past incidents, follow up with search_backup_knowledge. It asks the API listBackupRuns?status=failed&limit=1 (without a run_id), then getBackupRun, listExecutionLogs?run_id&level=error,warn,warning&limit=20 and listBackupFixes?limit=3 in parallel; each call after the first counts as one more tool call against the caller's limit (8.2), and an API 429 is passed on with its wait. Any failed call is a tool error, except a 403 on the fixes (an older API's policy refuses them to SERVICE_CREDENTIAL), which leaves past_fixes_reference empty. An older API that ignores the status filter cannot name the latest failed run: the tool then asks for a run_id instead of guessing. Each error_logs entry is a log line's message; a log of no failed repository goes with the first failure.
  • Parameters:
    • run_id (integer, optional): Run ID to diagnose. If omitted, finds the most recent failed run.
  • Output:
    {
    "run_id": 149,
    "started_at": "2026-09-17T02:10:00Z",
    "duration_ms": 300000,
    "total_failed_repos": 1,
    "failures": [
    {
    "repository": "MishraShardendu22/legacy-tool",
    "error": "fatal: early EOF / index-pack failed",
    "error_logs": [
    "fatal: read error: Connection reset by peer",
    "Clone failed after 3 retries"
    ]
    }
    ],
    "past_fixes_reference": [
    {"fix_id": 12, "title": "Raise git http.postBuffer", "description": "Set http.postBuffer to 524288000 in the worker", "commit_hash": "e5b8d4f"}
    ],
    "status": "TRIAGED"
    }

Category 3: Semantic Search & AI Knowledge Base​

9. search_backup_knowledge​

  • Description: Performs hybrid search (combining dense vector embeddings in pgvector and PostgreSQL full-text search with Reciprocal Rank Fusion) across historical logs, errors, past incident fixes, and chat investigations.
  • Parameters:
    • query (string, required): Search query (e.g. "clone timeout RPC failed", "SSH authentication failure").
    • limit (integer, optional, default: 5, max: 20).
  • Behaviour: POSTs to <OBSERVATORY_URL>/search with the server's own credential (SERVICE_CREDENTIAL in X-Service-Credential, else the deprecated INTERNAL_SECRET in X-Internal-Secret) and X-Account-Id of the caller's account (the Observatory searches that account's knowledge only and uses its server OpenRouter keys, never a user's), and returns its answer. When that fails (neither credential set, no OBSERVATORY_URL, unreachable, non-200), the tool error names why; nothing else is searched (the former ILIKE fallback over the database is gone with the database).

Category 4: Archive & File Inspection​

Archives live in BACKUP_ARCHIVE_PATH (set it to the worker's _Repos directory) and are resolved by exact file name only, never by substring or outside that root. That directory is on the MCP host and holds the deployment owner's archives only, so these three tools work for the owner's account (1) and answer every other account with the tool error "archives are on your own machine; use the worker (github-backup-worker) there": other accounts' workers keep their archives on their own machines. repo_name must be owner/name (GitHub naming rules) or, for legacy archives, a bare repository name. Candidates, in order:

  1. the archive key the worker recorded for the repository (worker_repo_state, through the API's getRepositoryArchive, GET /api/repos/{owner}/{name}/archive, for an owner/name; keys that leave the root are ignored). No recorded state (404, also an API without the route) is no error. When the lookup fails otherwise (the API down, a 5xx), the archive is still found by the file names below, without the recorded checksum, and the answer's recorded_archive_error says why: the archives on this host stay usable when the API is not,
  2. <owner>__<repo>.bundle, then <owner>__<repo>.tar.gz (lower case),
  3. the legacy <repo>.tar.gz (as given, then case-insensitively when exactly one file matches).

Files are opened through os.Root, so neither .. nor a symbolic link leaves the root. .bundle archives need git on the MCP host (a clear tool error otherwise); each git command has a 3 minute timeout, bundles over 2 GiB are not unpacked, and scratch clones are always removed.

10. verify_archive_integrity​

  • Description: Computes the archive's SHA-256 and compares it with the checksum the worker recorded (archive_sha256 of getRepositoryArchive) when there is one (a mismatch is an error). Git bundles are checked with git bundle verify (header, refs, prerequisites) and unpacked into a scratch repository with git bundle unbundle, which checks every object (verify alone accepts a corrupted or truncated pack). tar.gz archives have every tar header read.
  • Parameters:
    • repo_name (string, required): owner/name, or a bare name for legacy archives.
  • Output (bundle):
    {
    "repository": "octo/repo",
    "archive": "octo__repo.bundle",
    "format": "bundle",
    "resolved_by": "worker_repo_state",
    "archive_size_bytes": 1048576,
    "sha256_checksum": "3a7b9c...",
    "expected_sha256": "3a7b9c...",
    "refs": ["refs/heads/main", "HEAD"],
    "pack_verified": true,
    "integrity_status": "VALID_UNCOMPROMISED"
    }
    A bundle larger than 2 GiB is not unpacked: pack_verified is false, pack_note says why and integrity_status is PACK_UNVERIFIED (the header and refs were checked, the pack was not).

11. inspect_archive_contents​

  • Description: Lists files without extracting the archive: tar headers for tar.gz, the tree of the bundle's default branch (its HEAD, else main, master or the first branch) for bundles, read from a bounded scratch clone.
  • Parameters:
    • repo_name (string, required)
    • prefix (string, optional): Filter paths starting with this prefix (e.g. .github/, src/).
    • limit (integer, optional, default: 50, max 200).

12. extract_backup_file​

  • Description: Returns the content of one file (at most 10 MB) from the tar.gz archive or from the bundle's default branch (git cat-file).
  • Parameters:
    • repo_name (string, required)
    • file_path (string, required): Relative path within the archive (e.g. README.md, package.json); .., absolute paths, backslashes and NUL are rejected.

Category 5: Remediation & Operational Actions​

13. trigger_backup_run​

  • Description: Queues an on-demand backup run for the caller's account through the backup API's POST <BACKEND_URL>/api/requests (queueBackupRequest), which applies runstore.QueueRequest: one pending request per account and target (a unique index, migration 000022), and the account's plan: none without a paid plan (402 PLAN_REQUIRED), 10 per hour on the paid plan, no limit for the owner. That account's worker claims pending requests at its next run; the tool does not start the worker. If a pending request of the same account for the same target exists, that request is returned with already_queued: true instead of queuing a duplicate, and it does not count against the limit. Past the limit the tool error says when the next request can be queued. Needs the write scope. The request carries the credentials of 8.2: the caller's own personal access token (the API records token:<id> as the requester), for the owner without one SERVICE_CREDENTIAL and X-Account-Id: 1 (the API records service:mcp), and without SERVICE_CREDENTIAL the deprecated INTERNAL_SECRET and X-Account-Id of the caller's account (requested_by is then mcp). It is sent with an Idempotency-Key and retried once after a transport error or a 5xx; the one-pending-request rule makes the retry safe (a request the first attempt queued comes back as already_queued). A call without credentials (the owner's with neither setting) or for another account without a token under SERVICE_CREDENTIAL is a tool error before any request, and so is a refusal of the API (its status and error code, such as 403 FORBIDDEN for a token without the write scope, 403 ACCOUNT_DISABLED, 402 PLAN_REQUIRED or 429 MANUAL_RUN_LIMIT). The answer has no created_at, and target_repo/reason are null when empty.
  • Parameters:
    • target_repo (string, optional): owner/name, validated and stored in lower case; omit it for all tracked repositories.
    • reason (string, optional): Stored with the request (at most 500 characters).
  • Output:
    {
    "request_id": 12,
    "status": "pending",
    "target_repo": "octo/repo",
    "requested_by": "mcp",
    "reason": "config changed",
    "already_queued": false,
    "message": "Backup run request queued; the worker picks it up on its next run."
    }
  • Safety Guardrail: Marked as an operational action. Clients such as Claude and Codex surface a user confirmation when it is invoked.

14. record_backup_fix​

  • Description: Registers a permanent remediation resolution for the caller's account through the backup API's POST <BACKEND_URL>/api/fixes (recordBackupFix, runs), optionally linked to one affected run of that account: a run that does not exist or is another account's answers 404 RUN_NOT_FOUND, the tool says the run does not exist, and nothing is stored. This preserves institutional knowledge so the AI agent and future runs know how an issue was resolved. Needs the write scope. The request carries the credentials of 8.2 and an Idempotency-Key: a new one per tool call, or the idempotency_key argument. It is retried once after a transport error or a 5xx with the same key, so the fix is stored once; an agent that did not get an answer can call again with the same idempotency_key and gets the stored fix back (already_recorded: true), while the same key with a different fix is refused.
  • Parameters:
    • title (string, required, at most 300 characters): Concise description of the fix (e.g. "Increased git clone postBuffer to 500MB").
    • description (string, required, at most 20000 characters): Detailed explanation of the root cause and applied fix.
    • author (string, required, at most 100 characters): Author identifier (e.g. "Claude Code", "Codex", or human user).
    • commit_hash (string, optional, 7 to 64 hexadecimal characters): Git commit hash containing the code fix.
    • affected_run_id (integer, optional): The backup run this fix addresses.
    • idempotency_key (string, optional, 1 to 200 printable ASCII characters): Makes retries of the call record the fix once.
  • Output:
    {
    "fix_id": 42,
    "title": "Increased git clone postBuffer to 500MB",
    "author": "Claude Code",
    "commit_hash": "e5b8d4f",
    "affected_run_id": 149,
    "already_recorded": false,
    "status": "RECORDED_IN_DATABASE"
    }

There is no report or e-mail tool: the product sends no e-mail (ADR 0020). An agent that wants a report writes it from the tools' answers; in the dashboard every answer of the assistant can be downloaded.


5. MCP Resources & Prompts Specifications​

In addition to tools, the MCP protocol supports Resources (data URIs readable by agents) and Prompts (pre-composed agent workflows):

5.1 MCP Resources​

URI PatternNameMIME TypeDescription
backup://system/healthSystem Health Stateapplication/jsonThe backup API's readiness (GET /readyz): database is connected, the API's word for its database when it is not ready (such as disconnected), or unknown when the API cannot be reached; and the server time
backup://runs/latestLatest Backup Run Summaryapplication/jsonId, status, start time and counts of the caller's most recent run (the API's getLatestBackupRun); {"status": "unknown"} when there is none or the read fails

Like the tools, reading a resource needs an authenticated caller and returns only that caller's account's data.

Repository and analytics resources are not implemented; use the list_tracked_repositories and get_backup_metrics tools.

5.2 MCP Prompts​

Prompt 1: diagnose-latest-failure​

  • Description: Automatically loads the latest failed run, queries execution logs, searches semantic past resolutions, and guides the LLM to provide a step-by-step remediation plan.
  • Arguments: None.
  • Template Context: Pre-fetches backup://runs/latest and injects system diagnostic instructions.

Prompt 2: audit-backup-health​

  • Description: Performs a complete health and storage audit of the backups: system health, tracked repositories, recent runs and archive storage.

A disaster-recovery prompt is not implemented; verify_archive_integrity, inspect_archive_contents and extract_backup_file cover a test restore.


6. Go Server Technical Architecture & Package Layout​

6.1 Package Layout​

The MCP server is part of the root Go module (github.com/MishraShardendu22/github-backup), not a separate module:

src/backend/github-backup-mcp/
├── cmd/github-backup-mcp/main.go # Entrypoint (--transport stdio|http|sse, --port)
├── internal/app/ # run.go (startup), http.go (Streamable HTTP), sse.go (legacy SSE)
├── config/config.go # Settings (BACKEND_URL, OBSERVATORY_URL, SERVICE_CREDENTIAL, MCP_AUTH_TOKEN, MCP_ACCOUNT_ID, MCP_PERSONAL_TOKEN, ...)
├── auth/ # Caller (principal in the request context), the Authenticator (personal tokens checked by the API, legacy token, Forget), ServiceAuth (the server's own credential)
├── server/server.go # mcp-go server, tool/resource registration, result sanitizing, request ID and rate limit middleware, NewAuthenticator
├── transport/ # RequirePrincipal (and the request's X-Request-ID), the stateless Streamable HTTP handler, account-bound SSE sessions
├── sanitizer/sanitizer.go # Token and secret redaction
├── tools/ # apiclient (the backup API client), observability, diagnostics, search, archives (+ archive_bundle, archive_resolve), remediation
├── resources/resources.go # backup:// resources and the two prompts
├── Dockerfile
└── README.md
  1. MCP SDK: github.com/mark3labs/mcp-go
    • Most robust, standard-compliant Go implementation of Model Context Protocol (v2024-11-05).
    • Built-in support for server.NewStdioServer, server.NewStreamableHTTPServer (used in stateless mode) and server.NewSSEServer.
    • Automatic JSON Schema generation from Go struct parameters via mcp.NewTool.
  2. Structured Logging: log/slog through src/platform/logging (shared with the API).
    • Logs write strictly to stderr so they do not corrupt the JSON-RPC pipe on stdout in stdio mode.
  3. CLI Flags: the standard flag package.

The server has no database driver: it reads and writes through the backup API with net/http.


6.3 Core Code Implementation Patterns​

A. Entry Point & Transports (src/backend/github-backup-mcp/internal/app/run.go)​

The entry point parses --transport (stdio, http or sse; anything else is an error) and --port, builds the logger with server.NewLogger (stderr), logs the settings it ignores (DATABASE_URL, RATELIMIT_BACKEND=postgres), and opens the rate limit ports without a database. For stdio it decides the caller (MCP_PERSONAL_TOKEN's account, checked with the API, or MCP_ACCOUNT_ID), calls server.NewServer, which registers the tools, resources and prompts, installs the result sanitizer and registers the configured secrets with it, and serves the protocol on stdin/stdout as that caller. For http it builds the authenticator (server.NewAuthenticator), applies the startup rule of 8.2, builds the server with the authenticator's Forget hook, and serves transport.NewStreamableHTTP (stateless Streamable HTTP, standalone GET stream disabled) at /mcp behind transport.RequirePrincipal, plus a public GET /health, and shuts down gracefully on SIGINT/SIGTERM; sse serves transport.NewSSE behind the same check.

B. Tool Registration Pattern (tools/caller.go, tools/diagnostics.go)​

A tool handler is wrapped in readTool, writeTool or ownerArchiveTool, which take the auth.Caller from the context (failing closed without one), check the scope (and, for archives, the owner's account) and pass the caller in. Every API call acts for that caller (tools.API, whose setAccountHeaders picks the one credential that acts for the caller's account, 8.2); a row of another account is reported exactly like a missing one. Condensed from diagnose_backup_failure:

s.AddTool(tool, readTool(func(ctx context.Context, req mcp.CallToolRequest, caller auth.Caller) (*mcp.CallToolResult, error) {
runID := int64(req.GetInt("run_id", 0))
if runID <= 0 {
latest, unfiltered, err := api.backupRuns(ctx, caller, 1, 1, "failed")
...
if len(latest) == 0 {
return mcp.NewToolResultText(`{"status": "CLEAN", ...}`), nil
}
runID = latest[0].ID
}
wg.Go(func() { detail, detailErr = api.backupRun(ctx, caller, runID) })
wg.Go(func() { logs, logsErr = api.executionLogs(ctx, caller, logFilter{runID: runID, levels: []string{"error", "warn", "warning"}, limit: 20}) })
wg.Go(func() { fixes, fixErr = api.backupFixes(ctx, caller, 3) })
wg.Wait()
...
}))

A tool that changes data uses writeTool, and its API call is a write: it needs a credential, carries an Idempotency-Key and is retried once after a transport error or a 5xx.


7. Client Configuration & Integration Guide​

7.1 Integration with OpenAI Codex​

Codex reads MCP servers from ~/.codex/config.toml (or a project's .codex/config.toml):

[mcp_servers.github-backup]
command = "<path-to-repo>/src/backend/github-backup-mcp/bin/github-backup-mcp"
args = ["--transport", "stdio"]

[mcp_servers.github-backup.env]
BACKEND_URL = "http://localhost:8080"
SERVICE_CREDENTIAL = "ghb_svc_<the mcp credential>"
BACKUP_ARCHIVE_PATH = "<path-to-repo>/src/services/github-backup-worker/_Repos"

codex mcp list shows the server once it is configured.


7.2 Integration with Claude Desktop​

Claude Desktop starts local MCP servers over standard input/output (stdio); no bearer token is needed because only the process that started the server can reach it. A stdio server acts for account MCP_ACCOUNT_ID (default 1, the owner) with read and write access, calling the API with SERVICE_CREDENTIAL; for another account give it that account's personal access token in MCP_PERSONAL_TOKEN (it then acts with the token's account and scopes).

Configuration:​

  • Linux: ~/.config/Claude/claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"github-backup": {
"command": "<path-to-repo>/src/backend/github-backup-mcp/bin/github-backup-mcp",
"args": ["--transport", "stdio"],
"env": {
"BACKEND_URL": "http://localhost:8080",
"MCP_PERSONAL_TOKEN": "ghb_pat_<your token>"
}
}
}
}

To use a remote server (the self-hosted MCP host, or --transport http), create a personal access token in the dashboard (Settings, Tokens; read, or read write for the remediation tools) and bridge the server through the mcp-remote package, which forwards stdio to a Streamable HTTP endpoint and adds the header. This follows mcp-remote's documented --header usage; keeping the token in env avoids problems with spaces in arguments:

{
"mcpServers": {
"github-backup-remote": {
"command": "npx",
"args": ["-y", "mcp-remote", "https://<your-deployment>/mcp", "--header", "Authorization:${MCP_AUTHORIZATION}"],
"env": { "MCP_AUTHORIZATION": "Bearer ghb_pat_<your token>" }
}
}
}

7.3 Integration with Claude Code (CLI)​

Local server over stdio:

claude mcp add github-backup \
--env BACKEND_URL="http://localhost:8080" --env MCP_PERSONAL_TOKEN="$GHB_TOKEN" \
-- /path/to/github-backup-mcp --transport stdio

Remote server over Streamable HTTP (the self-hosted MCP host's /mcp, or a local --transport http server), with a personal access token from the dashboard (Settings, Tokens) in GHB_TOKEN:

claude mcp add --transport http github-backup https://<your-deployment>/mcp \
--header "Authorization: Bearer $GHB_TOKEN"

or in a project .mcp.json (Claude Code expands ${VAR} from the environment):

{
"mcpServers": {
"github-backup": {
"type": "http",
"url": "http://localhost:8090/mcp",
"headers": { "Authorization": "Bearer ${GHB_TOKEN}" }
}
}
}

Verify connection:

claude mcp list

7.4 Remote Docker / HTTP Deployment (Multi-Agent & Team Access)​

For teams or agents running in cloud environments, the server can run as a container serving Streamable HTTP at /mcp on port 8090. The transport is stateless, so it can run as several replicas behind a load balancer. The image needs git for the .bundle archive tools and BACKUP_ARCHIVE_PATH pointing at the archives:

The image (src/backend/github-backup-mcp/Dockerfile) starts the Streamable HTTP transport (--transport http) and is already part of docker-compose.yml:

services:
github-backup-mcp:
build:
context: .
dockerfile: src/backend/github-backup-mcp/Dockerfile
ports:
- "8090:8090"
environment:
BACKEND_URL: http://caddy:8080 # the API gateway: identity, runs and insights by path; every tool goes through it
OBSERVATORY_URL: http://github-backup-observatory:8000
INTERNAL_SECRET: ${INTERNAL_SECRET:?...} # deprecated: sent only while SERVICE_CREDENTIAL is empty
SERVICE_CREDENTIAL: ${MCP_SERVICE_CREDENTIAL:-} # this server's own credential (ADR 0009)
MCP_AUTH_TOKEN: ${MCP_AUTH_TOKEN:-} # optional and deprecated: acts as the owner's account
MCP_PORT: "8090"
# The worker's git sink keeps its archives in _Repos on the shared volume.
BACKUP_ARCHIVE_PATH: /data/archives/_Repos
volumes:
- backups_data:/data/archives:ro

GET /health is served without a token for container health checks; every other route requires a credential (8.2).

Clients use http://<host>:8090/mcp with Authorization: Bearer <personal access token> (see 7.2 and 7.3), and each call runs for that token's account; GET /health is public. Requests that arrive over a loopback connection must name a localhost Host (DNS rebinding protection), so a reverse proxy on the same host must rewrite Host. The legacy --transport sse (/sse, /message) still works for a single instance only, because its sessions live in memory.

Client configuration for the HTTP transport:

{
"mcpServers": {
"github-backup-remote": {
"type": "http",
"url": "http://localhost:8090/mcp",
"headers": { "Authorization": "Bearer ghb_pat_<your token>" }
}
}
}

8. Security, Guardrails & Human-In-The-Loop (HITL)​

8.1 Read-Only vs State-Modifying Segregation​

Tools are explicitly classified into safety tiers, and the server enforces them with token scopes (8.2):

  • Safe / Read-Only (read scope): get_system_health, get_dashboard_summary, get_backup_metrics, list_tracked_repositories, list_backup_runs, get_backup_run_details, get_execution_logs, diagnose_backup_failure, search_backup_knowledge, verify_archive_integrity, inspect_archive_contents, extract_backup_file. The last three serve the owner's account only.
  • Operational / Mutation (write scope; clients should still ask the user). A read-only token gets the tool error "this token is read-only" and nothing happens:
    • trigger_backup_run: Queues a backup_run_requests row through the backup API's POST /api/requests; the worker runs the backup (clones and uploads) on its next run.
    • record_backup_fix: Stores a permanent fix through the backup API's POST /api/fixes.

8.2 Authentication, Accounts and Scopes​

Every request runs for one principal (tenancy.Principal: account, kind, scopes), carried in the request context as an auth.Caller to every tool and resource. A tool or resource without one fails closed. Code: src/backend/github-backup-mcp/auth, transport/auth.go, tools/caller.go.

HTTP transports (--transport http and --transport sse) put every route except GET /health behind transport.RequirePrincipal, which reads Authorization: Bearer <token> (scheme case-insensitive) and accepts:

  • Personal access tokens (ghb_pat_ plus 43 base64url characters), created in the dashboard (Settings, Tokens) with the read or read write scopes and an expiry (30, 90 or 365 days, or never). Each call runs for the token's account with its scopes. They are verified by the backup API (the server has no database):

    • with the server's own credential: with the backup API's internal POST <BACKEND_URL>/api/internal/tokens/resolve ({"token"} in the body, SERVICE_CREDENTIAL in X-Service-Credential or, without it, the deprecated INTERNAL_SECRET in X-Internal-Secret, never both and no X-Account-Id, and X-Client-Address with the client's address as this server determined it, below). The API answers exactly what GET /api/me would and counts unknown tokens against that client's address, not this server's, so one client's made-up tokens cannot exhaust the API's budget for every other user. A 401 without a reason or a 403 there means the API refused the credential (503, not cached, not counted; for SERVICE_CREDENTIAL the error says the API's SERVICE_CREDENTIALS must hold its hash under the name mcp); an API without the route (404) is asked GET /api/me instead, with one warning in the log;
    • without one: with the backup API's GET <BACKEND_URL>/api/me, sending the token as the bearer.

    Only an answer whose principal.kind is personal_token counts. Successful answers are cached for 10 seconds (auth.MeCacheTTL) under the token's SHA-256 (the token itself is never stored; at most 1024 entries, expired ones evicted first), refusals (401) for 30 seconds in a second cache of the same size; failures are not cached. A token revoked in the dashboard stops working for the tools that forward it within about 2 seconds, when every API process refuses it: the first such refusal (401) also drops the token from both caches (Authenticator.Forget), so the next request is checked again and answered 401. The archive tools, get_system_health and search_backup_knowledge do not forward the token and keep working for at most the 10 seconds of the cache. The API's 401 names why (error.details.reason: unknown, revoked or expired); a 429 of the API is passed on as 429 with its Retry-After (60 s when it has none), not as 503.

  • The legacy MCP_AUTH_TOKEN (deprecated): when set to at least 32 characters (after surrounding whitespace is trimmed; shorter is treated as unset, matching the INTERNAL_SECRET rule), it acts as the owner's account (1) with read and write. Its SHA-256 is compared with the presented token's in constant time, so timing leaks neither the token nor its length. The first use logs a one-time deprecation warning pointing to personal tokens. Migrate each client to its own personal token, then unset it.

Refused: agent tokens (ghb_agt_, only for linked workers' /v1 routes at the API), dashboard session JWTs (the dashboard and the Observatory use those) and anything else. Answers:

  • 401 with WWW-Authenticate: Bearer realm="github-backup-mcp": no credentials, or an unknown, revoked, expired or wrongly shaped token, or a refused kind;
  • 403: a valid token of a disabled account;
  • 429 with Retry-After: the client's address sent too many unknown tokens (below), or the backup API rate limited the token check (with the server's own credential: the API's limit for this client's address);
  • 503: the token cannot be checked right now (the backup API failed), or the server can verify no credential at all.

Unknown tokens per address. Like the API, the server counts unknown or malformed tokens per client address (auth.TokenFailureMax, 60 a minute): past it the address gets 429 for any credential until the minute ends, without a lookup. Revoked or expired tokens, a disabled account's tokens, agent tokens and session JWTs (a misconfigured client, not guessing) and failed lookups do not count. Together with the refusal cache this bounds the token checks made-up tokens cause at the API, which applies the same limit: with the server's own credential per client (X-Client-Address, this server's determination of the address), so a client past it is turned away there too while every other client keeps working; without one per address, where every check comes from this server's one address and one client can make the API answer 429 for everyone for the rest of the minute (give the server SERVICE_CREDENTIAL). The client address is the connection's peer, unless the peer is listed in TRUSTED_PROXIES (comma-separated IPs or CIDRs), whose TRUST_PROXY_HEADER (default X-Forwarded-For) is then read from the right exactly as at the API (src/platform/clientip); a client's own X-Forwarded-For is never read. Behind a reverse proxy (Caddy on the self-hosted machine), list it in TRUSTED_PROXIES.

Tool calls per account. Each account may make config.ToolCallRateLimitMax (120) tool calls a minute, whichever token or transport it uses (a tool middleware in server.NewServer, so stdio as well). A call past it does not run and answers the tool error rate limit exceeded, retry in Ns. Every backup API call a tool makes after its first counts as one more tool call (tools.WithCallLimit), so diagnose_backup_failure, which makes up to four, costs four: the API allows 300 requests a minute per account, shared with the dashboard. A call the limit refuses midway ends the tool with the same error. A tool whose API call the API rate limited (429) answers a tool error with the API's code and retry in Ns from its Retry-After (60 s without one).

These limits count in each process with RATELIMIT_BACKEND=memory (the default: replicas and serverless instances count separately) and across instances with valkey. postgres needs a database the server does not have: it counts in process instead and logs a warning at startup.

Request IDs. Every backup API call carries an X-Request-ID: over HTTP the MCP client's own when it is one the API keeps ([A-Za-z0-9._-], at most 64 characters; transport.RequirePrincipal takes it, token checks included), otherwise a new one per tool call (a tool middleware), so one tool call's requests share an ID in the API's logs. The API's error message names its request ID, and so does the tool error.

Error bodies say why but never contain the token, and the sanitizer redacts ghb_pat_/ghb_agt_/ghb_svc_ tokens from tool output (8.3).

Scopes. trigger_backup_run and record_backup_fix need write; every other tool and the resources need read (which write implies, and every accepted principal holds).

Owner-only archives. The archive tools read the MCP host's disk, which holds the owner's archives only; they answer every other account with a tool error (Category 4).

SSE sessions are bound to the account that opened them: the session ID is <account id>.<32 random hex digits>, and a message posted to it with another account's token is refused like an unknown session (400). Each message runs as the caller who posted it.

stdio is reachable only by the local process that started the server. With MCP_PERSONAL_TOKEN it runs as that token's account with its scopes: the token is checked with the backup API once at startup (retried while the API is unavailable, for 15 seconds or the MCP_API_WAIT_SECONDS that is set, so the server still answers initialize within the 60 seconds that clients built on the MCP TypeScript SDK wait; not retried when the API refuses the server's own credential), every tool call forwards it, and MCP_ACCOUNT_ID must name the same account or be unset (the server refuses to start otherwise, and for an unknown, revoked or expired token or a disabled account). Without it, stdio runs as account MCP_ACCOUNT_ID (default 1, the owner) with read and write, calling the API with SERVICE_CREDENTIAL, which the API lets act for the owner only: another account without MCP_PERSONAL_TOKEN is refused at startup, unless the server still calls with the deprecated INTERNAL_SECRET (which may name any account). An MCP_ACCOUNT_ID that is not a positive integer is refused as well. The HTTP transports ignore MCP_ACCOUNT_ID and MCP_PERSONAL_TOKEN.

Startup rule. MCP_AUTH_TOKEN is optional. Every transport refuses to start with a SERVICE_CREDENTIAL that is not ghb_svc_ and 43 base64url characters (the log names the setting, never its value), and warns once when it calls with INTERNAL_SECRET because SERVICE_CREDENTIAL is unset. The HTTP servers start when personal tokens can be verified (a backup API at BACKEND_URL that answers GET /api/me and, with SERVICE_CREDENTIAL or INTERNAL_SECRET, accepts it on POST /api/internal/tokens/resolve, probed for up to MCP_API_WAIT_SECONDS, default 90, with waits of 1, 2, 4 and then 8 seconds, each failure logged with the next wait; an API that refuses the server's own credential is not asked again) or MCP_AUTH_TOKEN is set, and refuse to start otherwise. In both compose files the container starts only once Caddy and identity are healthy, gets MCP_API_WAIT_SECONDS from the stack's settings and has a health check start_period of that many seconds (the image's own is 90). With only MCP_AUTH_TOKEN and an unreachable API they start with a warning; personal tokens work once the API answers. The serverless handler cannot refuse to start: it answers 503 per request instead, also to every request, health included, while SERVICE_CREDENTIAL is malformed.

Calls to other services act for the caller's account, with one credential per request:

  • the backup API (every tool and resource but the archive files): the caller's own personal token as the bearer (HTTP, or stdio with MCP_PERSONAL_TOKEN), so the API applies its scopes and names it as the actor; for the owner without one (stdio, MCP_AUTH_TOKEN), SERVICE_CREDENTIAL plus X-Account-Id: 1, the only account the API's policy (routes/service.policy.go) lets the server's credential act for; another account without a token is refused before the call. Without SERVICE_CREDENTIAL: the deprecated INTERNAL_SECRET plus X-Account-Id for every caller, and without it either, the caller's token, the owner's reads without credentials (served by an API with API_REQUIRE_AUTH=false; writes are refused) and any other account's refused;
  • the Observatory (/search), which takes no personal token: SERVICE_CREDENTIAL (else INTERNAL_SECRET) plus X-Account-Id of the caller's account;
  • token checks: the credential alone, for no account (above).

The API's policy gives the mcp caller resolveToken for no account and, for the owner's account only, queueBackupRequest, recordBackupFix, listBackupRuns, getBackupRun, getLatestBackupRun, listExecutionLogs, listBackupFixes, getDashboardStats, getRunMetrics, listRepositories and getRepositoryArchive: exactly the server's calls (the readiness route GET /readyz is public and gets no credential). Before the server gets SERVICE_CREDENTIAL, the API and the Observatory must hold its hash under the name mcp (github-backup-api service-credential new mcp prints both).

These clients do not follow redirects, so a credential reaches only the configured service. No CORS headers are sent: MCP clients are not browsers, and a wildcard origin would let any web page call the tools.

Follow-up: OAuth 2.1 for remote connectors. Connectors that cannot be given a static header, such as claude.ai's remote MCP connectors, discover authorization through OAuth 2.1 as the MCP authorization specification describes: the server publishes RFC 9728 protected-resource metadata (/.well-known/oauth-protected-resource, also named in the resource_metadata parameter of the WWW-Authenticate challenge) that points to an authorization server, and the client obtains a short-lived access token for the account with PKCE (RFC 8414 server metadata, dynamic client registration). That needs an authorization server (consent page in the dashboard, token and refresh endpoints at the API) and is not part of this release; mcp-go already offers WithProtectedResourceMetadata for the resource side. Until then, use a personal token with mcp-remote (7.2) or a client that sends headers.

8.3 Sensitive Secret Redaction​

A tool handler middleware passes the text of every tool result, errors included, through sanitizer.SanitizeResult (the tools also call it on their own output). Text that is valid JSON, as most results are, is decoded (numbers are kept as written), every string, object key and number in it is sanitized on its own, and it is encoded again in its own layout: compact, or indented as json.MarshalIndent writes it, with members in their original order. JSON with nothing to redact is returned unchanged. Running the rules over JSON text instead would see the escaping rather than the strings, leaking a quoted value or corrupting the JSON. Other text is sanitized as it is. sanitizer.Sanitize redacts:

  1. GitHub tokens: ghp_ (classic PAT), gho_ (OAuth), ghu_ (App user-to-server), ghs_ (App installation), ghr_ (refresh) with 36 or more characters, and fine-grained github_pat_ tokens.
  2. Passwords in PostgreSQL URLs, including driver suffixes such as postgresql+asyncpg://.
  3. OpenRouter API keys (sk-or-v1-[a-f0-9]{64}), Bearer tokens (including +, / and =), and Basic credentials after an Authorization header name.
  4. Key-value secrets: the value after password=, passwd= or secret=, including keys that end in them such as DB_PASSWORD= or client_secret=. A value in double, single or JSON-escaped (\"...\") quotes is redacted whole; an unquoted one runs to the next whitespace, &, ;, ,, quote or backslash. In JSON, the string or number value of a member whose key ends in password, passwd or secret is redacted whole, and Authorization and Proxy-Authorization members (strings, or lists of them as http.Header encodes them) are sanitized as header values.
  5. The configured secret values, raw and JSON-escaped: SERVICE_CREDENTIAL, INTERNAL_SECRET, MCP_AUTH_TOKEN, MCP_PERSONAL_TOKEN, the DATABASE_URL password (the server ignores the setting but a shared .env may hold it), and JWT_SECRET when it is set in the MCP environment (values under 8 characters are skipped).
  6. This system's own tokens: personal access tokens (ghb_pat_), agent tokens (ghb_agt_) and service credentials (ghb_svc_).

8.4 Resource Bounds & Tar Bomb Protection​

  • Single-file extraction (extract_backup_file) is restricted to files $\le 10\text{MB}$ to prevent memory exhaustion.
  • Path traversal protection enforces that extracted paths cannot escape the sandbox boundary (rejects ../ sequences).
  • Archives are resolved by exact name inside BACKUP_ARCHIVE_PATH through os.Root (see Category 4), so repo_name cannot select files elsewhere on the host.
  • Bundle operations run git through src/platform/gitexec (argv only, no prompts, process group killed on timeout) with a 3 minute timeout per command, skip unpacking bundles over 2 GiB and remove their scratch clones.
  • Backup API calls have strict timeouts (5 s per request, 10 to 15 s per tool) to avoid hanging client requests, and at most 4 MiB of an answer is read.

9. Phased Implementation Roadmap​

┌───────────────────────────────────────────────────────────────────────────────┐
│ MCP SERVER IMPLEMENTATION PHASES │
├───────────────────────────────────────────────────────────────────────────────┤
│ Phase 1: Foundation & Stdio Transport │
│ • Initialize Go module `mcp-server` │
│ • Setup `mark3labs/mcp-go` and Stdio lifecycle │
│ • Establish pgxpool database connection & health check tool │
│ │
│ Phase 2: Observability & Diagnostics Tools │
│ • Port dashboard statistics, run history, and execution log queries │
│ • Implement compound `diagnose_backup_failure` triage tool │
│ • Connect `search_backup_knowledge` to Python Observatory / pgvector │
│ │
│ Phase 3: Archive Inspection & Fix Management │
│ • Implement tar header inspection and SHA-256 integrity verification │
│ • Implement `record_backup_fix` for logging permanent hotfixes │
│ • Add safe single-file extraction sandbox │
│ │
│ Phase 4: MCP Resources, Prompts & Client Wiring │
│ • Register `backup://` resources and diagnostic prompt templates │
│ • Generate client configs for Claude Desktop, Claude Code and Codex │
│ • Add Makefile targets: `make mcp-build`, `make mcp-run` │
└───────────────────────────────────────────────────────────────────────────────┘

Next Steps & Action Items​

  1. Review and approve the design document.
  2. Create feature branch: MishraShardendu22/main/go-mcp-server.
  3. Implement Phase 1 skeleton in src/backend/github-backup-mcp/.
  4. Register the MCP server with Claude Code (claude mcp add) or Codex (~/.codex/config.toml) to test it.