mcpkit

module
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2026 License: MIT

README

mcpkit

Go Reference Go Report Card Go CI MCP

The Go toolkit for production-grade MCP servers.

Built on github.com/mark3labs/mcp-go, mcpkit provides the middleware, type safety, and operational patterns needed to run MCP servers in production. It targets the MCP 2025-11-25 spec with 100% feature coverage.

Features

  • 100% MCP 2025-11-25 spec coverage — tools, resources, prompts, sampling, logging, elicitation, structured output, async tasks
  • 36 packages across 4 dependency layers — use only what you need; all packages are independently importable
  • 85%+ test coverage across all packages — comprehensive coverage with -race detection
  • Dual-SDK support — works with mcp-go today; //go:build official_sdk tags enable migration to the official Go SDK without rewriting tool code
  • Typed handlersTypedHandler[In, Out] generates schemas from Go structs, populates structuredContent, and eliminates manual JSON wiring
  • Middleware chain — composable middleware applied per-tool or globally; standard signature across all packages
  • Response truncation — configurable byte-budget middleware that caps oversized tool responses and appends guidance messages (middleware/truncate)
  • Production resilience — circuit breakers, rate limiters, and caching via the resilience package
  • Auth — JWT/JWKS validation, OAuth 2.1 discovery and client flow, Bearer middleware, DPoP proof validation, workload identity (GCP/AWS)
  • RBAC and audit logging — role-based tool access control and structured audit trails via the security package
  • Tenant isolation — tenant context propagation middleware for multi-tenant servers
  • Multi-agent orchestration — fan-out, pipeline, and select patterns (orchestrator); manager/agent-as-tool delegation (handoff)
  • Workflow engine — cyclical graph execution with conditional branching, checkpoints, and state machines (workflow)
  • Cost management — token accounting, budget policies, dollar-cost estimation, scoped per-tenant/user/session budgets, time-windowed tracking (finops)
  • Testing infrastructure — test server/client, assertion helpers, session record/replay, golden file snapshots, benchmark helpers (mcptest)
  • Input/output sanitization — secret and PII redaction, injection filtering, URI validation with SSRF and path traversal protection (sanitize)
  • Tool integrity — SHA-256 fingerprinting and tamper detection for registered tools (registry)
  • Gateway — multi-server aggregation with namespaced tool routing and per-upstream resilience policies (gateway)
  • Agent memory — episodic/semantic/procedural memory tiers with pluggable storage backends (memory)
  • Skills — context-aware lazy tool loading with skill bundles and triggers (skills)
  • Autonomous loops — the Ralph Loop pattern for iterative, self-directing task execution (ralph)
  • MCP-A2A bridge — bidirectional MCP/A2A protocol bridge: expose MCP tools as A2A skills and consume A2A agents as MCP tools (bridge/a2a) (docs)
  • Multi-protocol gateway — single HTTP endpoint serving MCP, A2A, and OpenAI function calling via automatic protocol detection and canonical translation (gateway/multi) (docs)

Quick Start

go get github.com/hairglasses-studio/mcpkit@latest
package main

import (
    "context"
    "log"

    "github.com/hairglasses-studio/mcpkit/handler"
    "github.com/hairglasses-studio/mcpkit/registry"
)

type GreetInput struct {
    Name string `json:"name" jsonschema:"required,description=Name to greet"`
}

type GreetOutput struct {
    Message string `json:"message"`
}

func main() {
    td := handler.TypedHandler[GreetInput, GreetOutput](
        "greet", "Greet a user by name",
        func(ctx context.Context, in GreetInput) (GreetOutput, error) {
            return GreetOutput{Message: "Hello, " + in.Name + "!"}, nil
        },
    )

    s := registry.NewMCPServer("greeter", "1.0.0")
    registry.AddToolToServer(s, td.Tool, td.Handler)

    if err := registry.ServeStdio(s); err != nil {
        log.Fatal(err)
    }
}
go run main.go                                          # stdio server
npx @modelcontextprotocol/inspector go run main.go      # interactive debugger

QUICKSTART.md has the full 5-stage progressive tutorial: hello world, typed parameters, middleware, resources and prompts, and testing with mcptest.

Package Map

Package Purpose Internal Deps
registry Tool registration, middleware chain, server integration, tool integrity verification none
handler TypedHandler generics, param extraction, result builders, elicitation registry
middleware/truncate Response size limiting with byte budgets, configurable guidance messages, error passthrough registry
resilience CircuitBreaker, RateLimiter, CacheEntry generics, middleware registry
mcptest Test server/client, assertion helpers, HTTP pool, session replay, snapshot testing, benchmark helpers registry
auth JWT/JWKS validation, OAuth discovery + client flow, Bearer middleware, DPoP proof validation + HTTP middleware, workload identity (GCP/AWS), context identity registry, client
security RBAC, audit logging middleware, tenant context propagation registry, auth
health Health check endpoint and checker registry none
observability OpenTelemetry tracing/metrics middleware registry
sanitize Input/output sanitization, secret/PII redaction, URI validation none
secrets Secret provider interface, env/file providers, sanitizer none
client HTTP pool and client utilities none
discovery MCP Registry client for server discovery and publishing, multi-registry metadata extraction registry, client, resources, prompts
resources Resource registry, middleware chain, server integration for URI-based data, URI validation middleware registry
prompts Prompt registry, middleware chain, server integration for reusable templates registry
logging slog.Handler bridge to MCP clients, tool invocation logging middleware registry
sampling Sampling client interface, context injection middleware, request builders registry
roots Client workspace root discovery, caching, context helpers registry
research MCP ecosystem monitoring and viability assessment tools registry, handler, client
gateway Multi-server aggregation with namespaced tool routing, per-upstream resilience (circuit breaker, rate limit, timeout) registry, client, resilience
dispatcher Priority worker pool with concurrency groups, middleware integration registry
ralph Autonomous loop runner for iterative task execution (Ralph Loop pattern) registry, handler, sampling, finops
finops Token accounting, budget policies, usage tracking middleware, dollar-cost estimation, scoped budgets, time-windowed tracking registry
memory Agent memory registry with pluggable storage backends registry
skills Context-aware lazy tool loading with skill bundles and triggers registry
handoff Agent delegation protocol with manager/agent-as-tool patterns, delegate middleware registry, sampling, finops
orchestrator Multi-agent execution patterns: fan-out, pipeline, select, stage middleware none
workflow Cyclical graph engine with conditional branching, checkpoints, state machines, node middleware orchestrator, registry, sampling
extensions MCP Extensions negotiation and capability handshake none
lifecycle Production server lifecycle: signal handling, graceful drain, shutdown hooks none
bootstrap Agent workspace init, context reports, capability matrix registry, resources, prompts, extensions
eval Evaluation framework: cases, scorers, JSON suite loading, runner registry
roadmap Machine-readable roadmap management, gap analysis, query functions registry, handler
rdcycle R&D cycle orchestration tools: scan, plan, verify, commit, report registry, handler, research, roadmap, workflow, finops
bridge/a2a Bidirectional MCP/A2A bridge: tool-to-skill translation, agent card generation, bridge executor, remote agent consumer registry, handler
gateway/multi Multi-protocol HTTP gateway: MCP, A2A, and OpenAI adapters with auto-detection and canonical translation registry

Dependency Layers

Layer 4  orchestrator ─ handoff ─ workflow ─ bootstrap
            │              │          │
Layer 3  security ── gateway ── ralph ── skills ── rdcycle
            │           │         │                  │
Layer 2  handler ─ auth ─ resilience ─ mcptest ─ finops ─ eval
         resources ─ prompts ─ discovery ─ sampling ─ ...
            │           │           │
Layer 1  registry ── health ── sanitize ── secrets ── client
         (no internal dependencies)
  • Layer 1 (no internal deps): registry, health, sanitize, secrets, client
  • Layer 2 (depend on Layer 1): resources, prompts, handler, resilience, middleware/truncate, mcptest, auth, observability, logging, sampling, roots, research, discovery, dispatcher, extensions, memory, finops, lifecycle, eval, roadmap, gateway/multi
  • Layer 3 (depend on Layer 2): security, gateway, ralph, skills, rdcycle
  • Layer 4 (depend on Layer 3): orchestrator, handoff, workflow, bootstrap

Lower layers never import upper layers. All packages in a layer can be used independently.

Commands

go build ./...           # Build all packages
go vet ./...             # Static analysis
go test ./... -count=1   # Run all tests (no cache)
make check               # All three above
make build-official      # Verify official SDK build
make check-dual          # Full check + official SDK build

License

See LICENSE for details.

Directories

Path Synopsis
Package a2a implements an A2A (Agent-to-Agent) Protocol v1.0 bridge for mcpkit.
Package a2a implements an A2A (Agent-to-Agent) Protocol v1.0 bridge for mcpkit.
Package a2h provides types for the Agent-to-Human (A2H) protocol.
Package a2h provides types for the Agent-to-Human (A2H) protocol.
Package agent provides core types for agent execution threads and events.
Package agent provides core types for agent execution threads and events.
Package auth provides authentication and authorization utilities for MCP servers.
Package auth provides authentication and authorization utilities for MCP servers.
Package bootstrap provides agent workspace initialization and capability reporting.
Package bootstrap provides agent workspace initialization and capability reporting.
bridge
a2a
Package a2a implements a bidirectional bridge between MCP (Model Context Protocol) tool registries and the A2A (Agent-to-Agent) Protocol v1.0.
Package a2a implements a bidirectional bridge between MCP (Model Context Protocol) tool registries and the A2A (Agent-to-Agent) Protocol v1.0.
openapi
Package openapi bridges OpenAPI v3 specifications to MCP tool registries.
Package openapi bridges OpenAPI v3 specifications to MCP tool registries.
Package client provides shared HTTP client utilities for MCP tool modules.
Package client provides shared HTTP client utilities for MCP tool modules.
cmd
rdloop command
Command rdloop runs autonomous R&D cycles using the Ralph Loop pattern.
Command rdloop runs autonomous R&D cycles using the Ralph Loop pattern.
Package device provides cross-platform abstractions for input device discovery, connection, event reading, and feedback output.
Package device provides cross-platform abstractions for input device discovery, connection, event reading, and feedback output.
Package discovery provides MCP Registry integration for server discovery, publishing, metadata extraction, and server card serving.
Package discovery provides MCP Registry integration for server discovery, publishing, metadata extraction, and server card serving.
Package dispatcher provides a priority worker pool with concurrency groups and middleware integration for controlled parallel tool execution.
Package dispatcher provides a priority worker pool with concurrency groups and middleware integration for controlled parallel tool execution.
Package eval provides an evaluation framework for scoring MCP tool accuracy.
Package eval provides an evaluation framework for scoring MCP tool accuracy.
ab
Package ab provides a framework for A/B testing prompt variants.
Package ab provides a framework for A/B testing prompt variants.
examples
a2a-bridge command
Command a2a-bridge demonstrates exposing mcpkit MCP tools as an A2A agent.
Command a2a-bridge demonstrates exposing mcpkit MCP tools as an A2A agent.
elicitation command
Command elicitation demonstrates MCP elicitation patterns for requesting additional information from the client during tool execution.
Command elicitation demonstrates MCP elicitation patterns for requesting additional information from the client during tool execution.
full command
Command full demonstrates a production-grade mcpkit MCP server with the full middleware stack: lifecycle, observability, finops, truncate, sanitize, security, and resilience.
Command full demonstrates a production-grade mcpkit MCP server with the full middleware stack: lifecycle, observability, finops, truncate, sanitize, security, and resilience.
gateway command
Command gateway demonstrates a production-grade mcpkit gateway server that aggregates tools from multiple upstream MCP servers into a single namespaced registry.
Command gateway demonstrates a production-grade mcpkit gateway server that aggregates tools from multiple upstream MCP servers into a single namespaced registry.
http command
Command http demonstrates a production-grade mcpkit StreamableHTTP server.
Command http demonstrates a production-grade mcpkit StreamableHTTP server.
minimal command
Command minimal demonstrates the simplest possible mcpkit MCP server.
Command minimal demonstrates the simplest possible mcpkit MCP server.
rdcycle command
Command rdcycle demonstrates the full R&D cycle: research + roadmap + rdcycle modules registered on a tool registry, wired into a workflow graph, and executed via ralph's WorkflowLoop.
Command rdcycle demonstrates the full R&D cycle: research + roadmap + rdcycle modules registered on a tool registry, wired into a workflow graph, and executed via ralph's WorkflowLoop.
stateless-http command
Command stateless-http demonstrates a horizontally scalable MCP server with Redis-backed sessions.
Command stateless-http demonstrates a horizontally scalable MCP server with Redis-backed sessions.
truncate-demo command
Command truncate-demo demonstrates the truncation middleware, which limits response size to prevent oversized payloads from consuming model context.
Command truncate-demo demonstrates the truncation middleware, which limits response size to prevent oversized payloads from consuming model context.
Package extensions implements MCP Extensions negotiation and capability handshake.
Package extensions implements MCP Extensions negotiation and capability handshake.
Package finops provides token accounting, budget policies, dollar-cost estimation, and usage tracking for MCP servers.
Package finops provides token accounting, budget policies, dollar-cost estimation, and usage tracking for MCP servers.
Package gateway aggregates tools from multiple upstream MCP servers into a single namespaced registry.
Package gateway aggregates tools from multiple upstream MCP servers into a single namespaced registry.
adapter
Package adapter defines the ProtocolAdapter interface for multi-protocol agent gateway support.
Package adapter defines the ProtocolAdapter interface for multi-protocol agent gateway support.
multi
Package multi implements a multi-protocol HTTP gateway for mcpkit.
Package multi implements a multi-protocol HTTP gateway for mcpkit.
Package handler provides helpers for building MCP tool handlers.
Package handler provides helpers for building MCP tool handlers.
Package handoff implements the agent delegation protocol for MCP servers.
Package handoff implements the agent delegation protocol for MCP servers.
Package health provides an HTTP health check endpoint and checker registry for MCP servers.
Package health provides an HTTP health check endpoint and checker registry for MCP servers.
Package hitools provides human interaction MCP tools built on mcpkit's elicitation primitives.
Package hitools provides human interaction MCP tools built on mcpkit's elicitation primitives.
Package lifecycle provides a production server lifecycle manager with OS signal handling, graceful drain, and LIFO shutdown hooks.
Package lifecycle provides a production server lifecycle manager with OS signal handling, graceful drain, and LIFO shutdown hooks.
Package logging bridges the standard slog package with MCP clients.
Package logging bridges the standard slog package with MCP clients.
Package mcptest provides testing infrastructure for MCP tool handlers.
Package mcptest provides testing infrastructure for MCP tool handlers.
Package memory provides an agent memory registry with pluggable storage backends.
Package memory provides an agent memory registry with pluggable storage backends.
middleware
debug
Package debug provides structured-logging middleware for mcpkit tool invocations.
Package debug provides structured-logging middleware for mcpkit tool invocations.
gate
Package gate provides a ToolCallGate middleware that pauses between tool selection and execution.
Package gate provides a ToolCallGate middleware that pauses between tool selection and execution.
prefetch
Package prefetch provides context pre-loading middleware for mcpkit tool invocations.
Package prefetch provides context pre-loading middleware for mcpkit tool invocations.
truncate
Package truncate provides response-size-limiting middleware for mcpkit tool invocations.
Package truncate provides response-size-limiting middleware for mcpkit tool invocations.
Package notify provides a notification abstraction with pluggable backends.
Package notify provides a notification abstraction with pluggable backends.
Package observability provides OpenTelemetry tracing and metrics for MCP servers via a drop-in registry.Middleware.
Package observability provides OpenTelemetry tracing and metrics for MCP servers via a drop-in registry.Middleware.
Package orchestrator provides multi-agent execution patterns for composing MCP tool calls.
Package orchestrator provides multi-agent execution patterns for composing MCP tool calls.
Package prompts provides a registry for MCP prompt templates.
Package prompts provides a registry for MCP prompt templates.
Package protocol provides MCP specification-compliant JSON-RPC 2.0 types, error codes, and helpers for building spec-conformant MCP servers.
Package protocol provides MCP specification-compliant JSON-RPC 2.0 types, error codes, and helpers for building spec-conformant MCP servers.
Package ralph implements the Ralph Loop pattern — an autonomous iterative task runner for MCP-based agents.
Package ralph implements the Ralph Loop pattern — an autonomous iterative task runner for MCP-based agents.
Package rdcycle provides R&D cycle orchestration tools for autonomous MCP development loops.
Package rdcycle provides R&D cycle orchestration tools for autonomous MCP development loops.
compat.go — MCP SDK compatibility / migration adapter layer (mcp-go variant).
compat.go — MCP SDK compatibility / migration adapter layer (mcp-go variant).
tasks
Package tasks provides async task lifecycle management for long-running MCP tool operations.
Package tasks provides async task lifecycle management for long-running MCP tool operations.
Package research provides MCP ecosystem monitoring and viability assessment tools.
Package research provides MCP ecosystem monitoring and viability assessment tools.
Package resilience provides fault-tolerance primitives for MCP tool handlers.
Package resilience provides fault-tolerance primitives for MCP tool handlers.
Package resources provides a registry for MCP resources and resource templates.
Package resources provides a registry for MCP resources and resource templates.
Package roadmap provides machine-readable roadmap management for MCP projects.
Package roadmap provides machine-readable roadmap management for MCP projects.
Package roots provides client workspace root discovery for MCP servers.
Package roots provides client workspace root discovery for MCP servers.
Package sampling provides a client interface, context helpers, and request builders for requesting LLM completions through the MCP sampling protocol.
Package sampling provides a client interface, context helpers, and request builders for requesting LLM completions through the MCP sampling protocol.
Package sanitize provides input validation, output redaction, and URI security for MCP tool parameters.
Package sanitize provides input validation, output redaction, and URI security for MCP tool parameters.
Package secrets provides a unified interface for retrieving secrets from multiple sources with caching and sanitization.
Package secrets provides a unified interface for retrieving secrets from multiple sources with caching and sanitization.
providers
Package providers implements concrete secret provider backends for the mcpkit secrets framework.
Package providers implements concrete secret provider backends for the mcpkit secrets framework.
Package security provides RBAC, audit logging, audit export, and tenant context propagation for MCP servers.
Package security provides RBAC, audit logging, audit export, and tenant context propagation for MCP servers.
Package session provides session management for MCP servers.
Package session provides session management for MCP servers.
Package skills provides context-aware lazy tool loading for MCP agents.
Package skills provides context-aware lazy tool loading for MCP agents.
Package slogcfg provides a shared structured logging configuration for MCP servers.
Package slogcfg provides a shared structured logging configuration for MCP servers.
testing
benchmark
Package benchmark provides cross-protocol performance benchmarks for mcpkit.
Package benchmark provides cross-protocol performance benchmarks for mcpkit.
conformance
Package conformance provides the "everything-server" for MCP conformance testing.
Package conformance provides the "everything-server" for MCP conformance testing.
conformance/cmd command
Command conformance-server runs the mcpkit everything-server on stdio for the official MCP conformance suite.
Command conformance-server runs the mcpkit everything-server on stdio for the official MCP conformance suite.
tck
Package tck provides a Technology Compatibility Kit for mcpkit servers.
Package tck provides a Technology Compatibility Kit for mcpkit servers.
Package toolindex provides discovery meta-tools for MCP tool registries.
Package toolindex provides discovery meta-tools for MCP tool registries.
Package transport provides a transport abstraction layer for MCP servers.
Package transport provides a transport abstraction layer for MCP servers.
Package trigger provides types and a registry for managing event sources that initiate agent actions.
Package trigger provides types and a registry for managing event sources that initiate agent actions.
Package workflow provides a cyclical graph engine for building stateful agent workflows with conditional branching, checkpoints, and rollback.
Package workflow provides a cyclical graph engine for building stateful agent workflows with conditional branching, checkpoints, and rollback.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL