micro--go-micro
524e16296b
* docs: update all four documentation guides and mark Q2 complete - ai-native-services: add WithMCP one-liner, standalone gateway, WebSocket client example, and OpenTelemetry observability section - mcp-security: add OTel distributed tracing, WebSocket authentication (connection-level and per-message), DeniedReason audit field - tool-descriptions: add manual overrides with WithEndpointDocs and export formats section - agent-patterns: add LangChain/LlamaIndex SDK pattern and standalone gateway production pattern with Docker example - Update roadmap: mark Q2 documentation as complete, Q2 at 100% - Update status: reflect all recent completions, shift priorities https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: add agent demo example and blog post Add examples/agent-demo with a multi-service project management app (projects, tasks, team) that demonstrates AI agents interacting with Go Micro services through MCP. Includes seed data and example prompts. Add blog post 4 "Agents Meet Microservices: A Hands-On Demo" walking through the example code and showing cross-service agent workflows. https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: enable multiple services in a single binary Remove global state mutations from service and cmd option functions so that configuring one service no longer overwrites another's settings. Key changes: - service/options.go: remove all DefaultXxx global writes from option functions; newOptions() now creates fresh Server, Client, Store, and Cache per service while sharing Registry, Broker, and Transport - cmd/cmd.go: newCmd() uses local copies instead of pointers to package globals; Before() no longer mutates DefaultXxx vars - cmd/options.go: remove global mutations from all option functions - service/service.go: export ServiceImpl type for cross-package use - service/group.go: new Group type for multi-service lifecycle - micro.go: add Start/Stop to Service interface, expose Group and NewGroup convenience function - examples/multi-service: working example with two services https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * docs: highlight multi-service binary support Add multi-service section to README with code example, update features list, add to examples index, and note in status summary. https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: unify service API and clean up developer experience - Unified service creation: micro.New("name", opts...) as canonical API - Clean handler registration: service.Handle(handler, opts...) accepts server.HandlerOption args directly, no need to reach through Server() - Unexported serviceImpl: users interact through Service interface only - Service groups use Service interface (not concrete type) - Fixed Stop() to properly propagate BeforeStop/AfterStop errors - Fixed store init: error-level log instead of fatal on init failure - Updated all examples to use consistent patterns - Updated README, getting-started, MCP docs, and guides - Added blog post about the DX cleanup https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * fix: add blog post 5 to blog index Blog post 5 (Developer Experience Cleanup) existed as a file but was missing from the blog index page. https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: make micro new generate MCP-enabled services by default - main.go template includes mcp.WithMCP(":3001") by default - Handler template has agent-friendly doc comments with @example tags - Proto template has descriptive field comments - README includes MCP usage, Claude Code config, and tool description tips - Makefile adds mcp-tools, mcp-test, mcp-serve targets - go.mod updated to Go 1.22 - Added --no-mcp flag to opt out of MCP integration - Post-create output shows MCP endpoint URLs https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * docs: add MCP migration guide and troubleshooting guide - Migration guide: 3 approaches to add MCP to existing services (WithMCP one-liner, standalone gateway, CLI) - Troubleshooting guide: common issues with agents, WebSocket, Claude Code, auth, rate limiting, and performance https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * refactor: rename model/ package to ai/ for AI model providers The model/ package name conflicted with the conventional use of "model" for data models. Renamed to ai/ which better describes the package's purpose (AI provider abstraction for Anthropic, OpenAI, etc.) and frees up model/ for future data model layer use. - Rename model/ → ai/ with package name change - Update all Go imports from go-micro.dev/v5/model to go-micro.dev/v5/ai - Update cmd/micro/server/server.go references (model.X → ai.X) - Update all documentation and roadmap references - All tests pass, CLI builds successfully https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: add model package for typed data access with CRUD and queries New model/ package provides a typed data model layer using Go generics. Supports structured CRUD operations, WHERE filters, ordering, pagination, and automatic schema creation from struct tags. Three backends: - memory: in-memory for development and testing - sqlite: embedded SQL for dev and single-node production - postgres: full PostgreSQL for production deployments Key features: - Generic Model[T] with Create/Read/Update/Delete/List/Count - Query builder: Where(), WhereOp(), OrderAsc/Desc(), Limit(), Offset() - Struct tags: model:"key" for primary key, model:"index" for indexes - Auto table creation from struct schema - 19 tests passing across memory and sqlite backends https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: add model code generation to protoc-gen-micro Extend the micro plugin to generate model structs from proto messages annotated with // @model. Generated alongside client/server code in the same .pb.micro.go file. For a proto message like: // @model message User { string id = 1; string name = 2; } Generates: - UserModel struct with model:"key" and json tags - NewUserModel(db) factory returning *model.Model[UserModel] - UserModelFromProto(*User) *UserModel converter - (*UserModel).ToProto() *User converter Supports @model(table=custom_table, key=custom_field) options. Adds GetComments() to generator for plugin comment inspection. https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: add Model() to Service interface for Client/Server/Model trifecta Every service now exposes Client(), Server(), and Model() — call services, handle requests, and save/query data from the same interface. Includes README docs, blog post, and a full model guide on the docs site. https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: add Helm chart for MCP gateway Kubernetes deployment Adds official Helm chart at deploy/helm/mcp-gateway/ with: - Deployment, Service, ServiceAccount templates - HPA for auto-scaling based on CPU/memory - Ingress with TLS support - Configurable registry (consul, etcd, mdns), rate limiting, JWT auth, audit logging, and per-tool scopes - Security context (non-root, read-only rootfs, drop all caps) - NOTES.txt with post-install connection instructions Updates roadmap and status docs to reflect Helm Charts as delivered. https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * docs: add Helm chart entry to changelog https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc * feat: add per-tool circuit breakers to MCP gateway Protects downstream services from cascading failures. When a tool's RPC calls fail repeatedly, the circuit opens and rejects requests immediately until the service recovers (half-open probe pattern). - CircuitBreakerConfig with MaxFailures, Timeout, MaxHalfOpen - Per-tool breakers created during service discovery - Integrated into HTTP call path with 503 response when open - Records success/failure after each RPC call - --circuit-breaker and --circuit-breaker-timeout CLI flags - 8 unit tests covering all state transitions https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc --------- Co-authored-by: Claude <noreply@anthropic.com>
243 行
6.1 KiB
Go
243 行
6.1 KiB
Go
// Command micro-mcp-gateway runs a standalone MCP gateway that discovers
|
|
// go-micro services via a registry and exposes them as AI-accessible tools
|
|
// through the Model Context Protocol.
|
|
//
|
|
// This is the production deployment binary for the MCP gateway, intended
|
|
// to run independently of your services.
|
|
//
|
|
// Usage:
|
|
//
|
|
// # mDNS (development default)
|
|
// micro-mcp-gateway --address :3000
|
|
//
|
|
// # Consul
|
|
// micro-mcp-gateway --address :3000 --registry consul --registry-address consul:8500
|
|
//
|
|
// # etcd
|
|
// micro-mcp-gateway --address :3000 --registry etcd --registry-address etcd:2379
|
|
//
|
|
// # With auth and rate limiting
|
|
// micro-mcp-gateway --address :3000 --registry consul \
|
|
// --rate-limit 100 --rate-burst 200 --audit
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/signal"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"go-micro.dev/v5/auth"
|
|
"go-micro.dev/v5/auth/jwt"
|
|
"go-micro.dev/v5/gateway/mcp"
|
|
"go-micro.dev/v5/registry"
|
|
"go-micro.dev/v5/registry/consul"
|
|
"go-micro.dev/v5/registry/etcd"
|
|
|
|
"github.com/urfave/cli/v2"
|
|
)
|
|
|
|
var version = "0.1.0"
|
|
|
|
func main() {
|
|
app := &cli.App{
|
|
Name: "micro-mcp-gateway",
|
|
Usage: "Standalone MCP gateway for go-micro services",
|
|
Version: version,
|
|
Flags: []cli.Flag{
|
|
&cli.StringFlag{
|
|
Name: "address",
|
|
Usage: "Address to listen on",
|
|
Value: ":3000",
|
|
EnvVars: []string{"MCP_ADDRESS"},
|
|
},
|
|
&cli.StringFlag{
|
|
Name: "registry",
|
|
Usage: "Service registry (mdns, consul, etcd)",
|
|
Value: "mdns",
|
|
EnvVars: []string{"MICRO_REGISTRY"},
|
|
},
|
|
&cli.StringFlag{
|
|
Name: "registry-address",
|
|
Usage: "Registry address (e.g., consul:8500, etcd:2379)",
|
|
EnvVars: []string{"MICRO_REGISTRY_ADDRESS"},
|
|
},
|
|
&cli.Float64Flag{
|
|
Name: "rate-limit",
|
|
Usage: "Requests per second per tool (0 = unlimited)",
|
|
EnvVars: []string{"MCP_RATE_LIMIT"},
|
|
},
|
|
&cli.IntFlag{
|
|
Name: "rate-burst",
|
|
Usage: "Rate limit burst size",
|
|
Value: 20,
|
|
EnvVars: []string{"MCP_RATE_BURST"},
|
|
},
|
|
&cli.BoolFlag{
|
|
Name: "auth",
|
|
Usage: "Enable JWT authentication",
|
|
EnvVars: []string{"MCP_AUTH"},
|
|
},
|
|
&cli.BoolFlag{
|
|
Name: "audit",
|
|
Usage: "Enable audit logging to stdout",
|
|
EnvVars: []string{"MCP_AUDIT"},
|
|
},
|
|
&cli.StringSliceFlag{
|
|
Name: "scope",
|
|
Usage: "Tool scope requirement (format: tool=scope1,scope2)",
|
|
},
|
|
&cli.IntFlag{
|
|
Name: "circuit-breaker",
|
|
Usage: "Circuit breaker max failures before opening (0 = disabled)",
|
|
EnvVars: []string{"MCP_CIRCUIT_BREAKER"},
|
|
},
|
|
&cli.DurationFlag{
|
|
Name: "circuit-breaker-timeout",
|
|
Usage: "Circuit breaker open-state timeout before half-open probe",
|
|
Value: 30 * time.Second,
|
|
EnvVars: []string{"MCP_CIRCUIT_BREAKER_TIMEOUT"},
|
|
},
|
|
},
|
|
Action: run,
|
|
}
|
|
|
|
if err := app.Run(os.Args); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func run(c *cli.Context) error {
|
|
logger := log.New(os.Stdout, "[mcp-gateway] ", log.LstdFlags)
|
|
|
|
// Configure registry
|
|
reg, err := newRegistry(c.String("registry"), c.String("registry-address"))
|
|
if err != nil {
|
|
return fmt.Errorf("registry: %w", err)
|
|
}
|
|
|
|
// Build MCP options
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
|
|
opts := mcp.Options{
|
|
Registry: reg,
|
|
Address: c.String("address"),
|
|
Context: ctx,
|
|
Logger: logger,
|
|
}
|
|
|
|
// Rate limiting
|
|
if rps := c.Float64("rate-limit"); rps > 0 {
|
|
opts.RateLimit = &mcp.RateLimitConfig{
|
|
RequestsPerSecond: rps,
|
|
Burst: c.Int("rate-burst"),
|
|
}
|
|
logger.Printf("Rate limit: %.0f req/s, burst %d", rps, c.Int("rate-burst"))
|
|
}
|
|
|
|
// Auth
|
|
if c.Bool("auth") {
|
|
opts.Auth = jwt.NewAuth()
|
|
logger.Printf("JWT authentication enabled")
|
|
}
|
|
|
|
// Scopes
|
|
if scopes := c.StringSlice("scope"); len(scopes) > 0 {
|
|
opts.Scopes = parseScopes(scopes)
|
|
for tool, s := range opts.Scopes {
|
|
logger.Printf("Scope: %s requires [%s]", tool, strings.Join(s, ", "))
|
|
}
|
|
}
|
|
|
|
// Circuit breaker
|
|
if maxFail := c.Int("circuit-breaker"); maxFail > 0 {
|
|
opts.CircuitBreaker = &mcp.CircuitBreakerConfig{
|
|
MaxFailures: maxFail,
|
|
Timeout: c.Duration("circuit-breaker-timeout"),
|
|
}
|
|
logger.Printf("Circuit breaker: max %d failures, timeout %s", maxFail, c.Duration("circuit-breaker-timeout"))
|
|
}
|
|
|
|
// Audit
|
|
if c.Bool("audit") {
|
|
opts.AuditFunc = func(r mcp.AuditRecord) {
|
|
status := "ALLOWED"
|
|
if !r.Allowed {
|
|
status = "DENIED:" + r.DeniedReason
|
|
}
|
|
logger.Printf("[audit] %s tool=%s account=%s status=%s duration=%s",
|
|
r.TraceID, r.Tool, r.AccountID, status, r.Duration)
|
|
}
|
|
logger.Printf("Audit logging enabled")
|
|
}
|
|
|
|
// Print startup info
|
|
logger.Printf("Starting MCP gateway on %s", c.String("address"))
|
|
logger.Printf("Registry: %s", c.String("registry"))
|
|
if addr := c.String("registry-address"); addr != "" {
|
|
logger.Printf("Registry address: %s", addr)
|
|
}
|
|
|
|
// Start gateway in background
|
|
errCh := make(chan error, 1)
|
|
go func() {
|
|
errCh <- mcp.ListenAndServe(opts.Address, opts)
|
|
}()
|
|
|
|
// Wait for signal or error
|
|
sigCh := make(chan os.Signal, 1)
|
|
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
|
|
|
|
select {
|
|
case sig := <-sigCh:
|
|
logger.Printf("Received %s, shutting down...", sig)
|
|
cancel()
|
|
return nil
|
|
case err := <-errCh:
|
|
return fmt.Errorf("gateway error: %w", err)
|
|
}
|
|
}
|
|
|
|
func newRegistry(name, address string) (registry.Registry, error) {
|
|
var opts []registry.Option
|
|
if address != "" {
|
|
opts = append(opts, registry.Addrs(strings.Split(address, ",")...))
|
|
}
|
|
|
|
switch name {
|
|
case "mdns", "":
|
|
return registry.NewMDNSRegistry(opts...), nil
|
|
case "consul":
|
|
return consul.NewConsulRegistry(opts...), nil
|
|
case "etcd":
|
|
return etcd.NewEtcdRegistry(opts...), nil
|
|
default:
|
|
return nil, fmt.Errorf("unknown registry %q (supported: mdns, consul, etcd)", name)
|
|
}
|
|
}
|
|
|
|
func parseScopes(raw []string) map[string][]string {
|
|
scopes := make(map[string][]string)
|
|
for _, s := range raw {
|
|
parts := strings.SplitN(s, "=", 2)
|
|
if len(parts) != 2 {
|
|
continue
|
|
}
|
|
tool := strings.TrimSpace(parts[0])
|
|
scopeList := strings.Split(parts[1], ",")
|
|
for i := range scopeList {
|
|
scopeList[i] = strings.TrimSpace(scopeList[i])
|
|
}
|
|
scopes[tool] = scopeList
|
|
}
|
|
return scopes
|
|
}
|
|
|
|
// Ensure auth.Auth interface is satisfied at compile time.
|
|
var _ auth.Auth = jwt.NewAuth()
|