convez.ai
MCP ServerIntegração & APIsAvançado
DISSIDIA-986

go-mcp-bridge

DISSIDIA-986/go-mcp-bridge

Bridge MCP seguro para plataforma de ticketing com autorização granular

Ver no GitHub
InicialPluginScore · de 0 a 100

Servidor MCP em Go que expõe uma plataforma de ticketing legada de forma segura para agentes LLM (Claude, Gemini). Implementa autorização estilo Figma, controle de escopo e fluxo completo de compra, reembolso e validação de ingressos via Protocol Context Model.

Instalação

$npx convez-ai DISSIDIA-986/go-mcp-bridge

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 5 meses
Versão
—
Issues abertas
0
Contribuidores
1

Casos de uso

  • Expor APIs legadas para agentes LLM sem risco de segurança
  • Fluxo de compra de ingressos automatizado com consentimento do usuário
  • Validação, reembolso e check-in de ingressos via agentes de IA
  • Integração de serviços existentes ao ecossistema MCP

Veredito

Referência técnica sólida e pronta para produção que resolve o problema real de expor serviços legados a agentes LLM mantendo segurança. Arquitetura bem documentada com exemplos reais de autorização, mas nicho específico (ticketing) — valor máximo para quem está integrando LLMs a plataformas existentes.

README

A tradução para o português deste README ainda está na fila.

go-mcp-bridge

Wrapping a traditional backend (a ticketing platform) with the Model Context Protocol so that any LLM agent — Claude Code, OpenAI Codex, Gemini CLI — can use it safely, behind a Figma-style authorization gate.

This is a compact, runnable reference for one of the most common questions in AI engineering right now: "We have existing services. How do we let an LLM use them without handing it the keys to everything?"

┌──────────────┐   stdio MCP    ┌──────────────┐   HTTP/JSON   ┌──────────────┐
│ LLM CLI      │ ─────────────► │ mcpserver    │ ────────────► │ apiserver    │
│ Claude /     │                │ (the bridge) │               │ (traditional │
│ Codex /      │ ◄───────────── │ tools +      │ ◄──────────── │  services)   │
│ Gemini       │   results      │ resources +  │               │  REST API    │
└──────────────┘                │ prompts +    │               └──────┬───────┘
                                 │ authz gate   │                      │
                                 └──────────────┘        ┌─────────────┼─────────────┐
                                                         ▼             ▼             ▼
                                                    PostgreSQL       Redis        RabbitMQ
                                                 (orders, seats,  (seat holds,  (payment audit
                                                  payments, auth)  auto-expiry)   events)

Demo

A real MCP client driving the server over stdio — discover → authorize → consent → hold → book → pay — with no LLM:

MCP client demo

The full ticketing flow including 验票/check-in, anti-passback, refund, and a read-only scope denial:

End-to-end demo

Architecture at a glance

System architecture (topology, data/control flow, correctness + security guarantees):

System architecture

Product architecture (the MCP surface and the human-in-the-loop authorization journey):

Product architecture


What is MCP, in one paragraph

The Model Context Protocol is a standard way for an LLM to discover and call external capabilities. An MCP server advertises three kinds of things, and an MCP client (the LLM host) consumes them:

PrimitiveWhat it isIn this project
ToolsFunctions the model can call (actions)authorize, get_token, list_events, get_event_seats, hold_seats, book_tickets, pay_order, cancel_order, query_orders, validate_ticket
ResourcesRead-only data the model can fetch by URIticket://events, ticket://events/{id}/seats
PromptsReusable prompt templates / workflowsbook_ticket_assistant, refund_assistant

Scenarios covered: 订票 (book) · 抢票 (concurrent holds, contention-safe) · 支付 (pay) · 退票 (refund) · 验票 (check-in/validation at the gate) · 查询 (query).

The key idea: the LLM never talks to your database. It talks to a small protocol server that you control, which decides what is exposed and enforces who is allowed to do what.


Why this design (the interview talking points)

  • Bridge, don't rewrite. apiserver is an ordinary REST service that knows nothing about AI. mcpserver is a thin adapter in front of it. You wrap what you already have.
  • The service owns authorization, not the bridge. Scopes are enforced in the REST layer (defense in depth). The bridge just forwards a bearer token.
  • Human-in-the-loop consent. Like the Figma MCP, an agent must request authorization and a human approves it out-of-band before any write tool works. Approval binds a user identity and a scope set into a short-lived, revocable token — so an agent can never act as a different user or beyond its grant.
  • Correctness under concurrency. Booking is transactional: a conditional UPDATE ... WHERE status='available', an affected-row check, and a UNIQUE(seat_id) backstop make double-selling a seat impossible even under a burst of parallel requests. Redis provides fast, auto-expiring holds on top.
  • Messaging off the critical path. Payment updates the order synchronously (correctness), and also emits a RabbitMQ event consumed for audit — so the message bus is demonstrated without becoming a correctness dependency.

Real production systems would point this at an on-prem / self-hosted LLM instead of a public CLI, and add mTLS + session-bound tokens + PKCE + an authenticated consent screen (here the approve endpoint trusts the posted user_id to simulate a logged-in human). This repo deliberately closes the holes that matter for the bridge itself — at tool-call time the user is derived from the token (no identity escalation), tokens expire and are revocable, and pay/refund/cancel row-lock the order so they can't double-charge — and documents the rest. See ARCHITECTURE.md.


Stack

A practical slice of the popular Go ecosystem (2026):

Huma v2 + chi (OpenAPI REST) · pgx + sqlc (type-safe SQL) · Redis (seat holds) · RabbitMQ via Watermill · Koanf (config) · Zap (logging) · OpenTelemetry (tracing) · Cobra (CLIs) · official modelcontextprotocol/go-sdk (MCP).


Quickstart

Two ways to run, both in OrbStack/Docker.

A. Infra in Docker, Go service on the host (fast iteration):

make up                  # Postgres / Redis / RabbitMQ
make seed                # demo events + seats
make apiserver           # REST API on :8263 (leave running)
./scripts/demo.sh        # narrated end-to-end demo (PAUSE=2 for a slower GIF)

B. Everything in Docker (the Go service is containerized too):

make up-all              # builds the image, starts infra + apiserver, seeds
./scripts/demo.sh        # same demo, now hitting the containerized service

make reset gives a pristine catalog before recording. make down wipes everything (-v). The auto-generated OpenAPI docs UI is at http://localhost:8263/docs (see docs/openapi-docs.png).


Driving it from an LLM CLI

The MCP server speaks stdio, so any MCP-capable host can launch it.

Claude Code — a project .mcp.json is already included:

make build                       # produces ./bin/mcpserver
claude   # it will discover the "ticketing" server from .mcp.json

Then ask, e.g.: "List the events and tell me how many seats are free for event 1." (read-only, no token needed).

Codex CLI — merge deploy/codex-config.toml into ~/.codex/config.toml (set the absolute binary path).

Gemini CLI — merge deploy/gemini-settings.json into your Gemini settings.

No LLM? Use the bundled MCP client. cmd/mcpclient is a real MCP client that spawns the server over stdio and runs the whole flow — discovery → browse → authorize → consent → token → hold → book → pay → query — with zero LLM/API keys. Great for an offline, reproducible demo:

make up && make seed && make apiserver   # (or make up-all)
make mcpclient                            # drives the server over real stdio
# real human gate instead of the simulated one:
go run ./cmd/mcpclient --server ./bin/mcpserver --auto-approve=false

The authorization dance (what makes it safe)

  1. Agent calls authorize with the scopes it needs → gets a grant code.
  2. A human approves out-of-band (the consent step):
    ./bin/mcpserver consent approve <code> --user jordan
    
  3. Agent calls get_token to retrieve the bearer token, then hold_seats → book_tickets → pay_order.

A read-only token calling hold_seats gets 403: token lacks required scope — the agent is told no, and nothing changes in the database.


What's verified (run it yourself)

make test                        # unit: scope logic, grant validity, normalization
make up && make e2e              # e2e against REAL Postgres/Redis/RabbitMQ + MCP

The e2e suite (18 tests, all green) covers the happy path and the failure paths that actually bite:

  • ✅ MCP tools/list exposes all 10 tools (with read-only/destructive annotations); static + templated resources resolve, malformed resource URIs rejected, both prompts resolve incl. argument templating
  • ✅ MCP over the real stdio transport (spawns the built binary), not just in-memory
  • ✅ full booking flow over MCP (hold → book → pay → query)
  • ✅ authorization gate: missing / bogus / revoked token, and insufficient-scope all rejected
  • ✅ double-sell prevented: 12 concurrent bookings of one seat → exactly 1 winner
  • ✅ double-charge prevented: 10 concurrent pays of one order → charged once (SELECT … FOR UPDATE)
  • ✅ 验票/check-in: validate once, second scan rejected (anti-passback), unpaid ticket rejected, wrong-scope rejected, 10 concurrent scans → admitted once
  • ✅ no enter-then-refund fraud: refund after check-in rejected, check-in after refund rejected, and a concurrent refund+check-in race never leaves a ticket both refunded AND checked-in (order-row lock on both paths)
  • ✅ expired hold can't be booked (real 1.5s timing)
  • ✅ hold conflict, empty input, oversized input (>50 seats), nonexistent order
  • ✅ real RabbitMQ publish → consume round-trip

Verified live with a real model (Claude Code over MCP):

DEMO A — full-scope token:  order 10 booked + paid, total $500, status succeeded
DEMO B — read-only token:   hold_seats -> "api error 403: token lacks required scope"
                            (seats stayed available — the agent was blocked)

Layout

cmd/apiserver     REST service (serve | seed)            — the traditional backend
cmd/mcpserver     MCP bridge   (serve | consent ...)     — the wrapper + consent CLI
cmd/mcpclient     standalone MCP client                  — drives the server, no LLM
internal/
  domain          types + pure rules (scopes, state)     — unit-tested
  auth            Figma-style consent + token validation
  ticket seat order payment   the four services
  cache           Redis seat holds (atomic Lua)
  mq              Watermill RabbitMQ publisher + audit consumer
  db, db/sqlc     pgx pool + sqlc-generated queries
  httpapi         Huma/chi routes + scope enforcement
  apiclient       HTTP client the bridge uses
mcp/server        MCP tools / resources / prompts
test/e2e          end-to-end against real infra
scripts/demo.sh   narrated demo for recording
ARCHITECTURE.md   design + the concurrency/auth hardening rationale
Ver o original no GitHub

Bom para

Relacionados