项目文件夹

0
Asim Aslam d3c4981326
goreleaser / goreleaser (push) Has been cancelled
Enhance AI service generation with prompt-based architecture and logic (#2926)
* feat: add micro new --prompt and micro run --prompt

Add AI-powered service generation: describe a system in natural
language and get real go-micro services with proto definitions,
handlers, doc comments, and MCP support.

micro new --prompt "a contact book with notes and tags" \
  --provider anthropic

Generates:
  contacts/ — CRUD service with name, email, phone fields
  notes/    — notes linked to contacts
  tags/     — tagging system

Each service gets:
  proto/{name}.proto   — domain model + CRUD endpoints
  handler/{name}.go    — in-memory store, @example tags for MCP
  main.go              — MCP-enabled, proper imports
  go.mod + Makefile     — compiles with go mod tidy + make proto

micro run --prompt does the same then starts all services.

The LLM designs the architecture (service names, fields, endpoints,
descriptions) and returns structured JSON. Code generation uses
the existing template patterns — the output is standard go-micro
code that compiles, runs, and is immediately callable via MCP
and micro chat. No AI dependency at runtime.

* feat: LLM generates real business logic with compile-fix loop

Rebuild the generate package so the LLM writes actual handler
code with business logic, not just CRUD scaffolding.

The flow is now:
1. LLM designs architecture (service names, fields, endpoints)
   → returns structured JSON
2. Proto, main.go, go.mod, Makefile generated deterministically
   from the design (guaranteed to be correct)
3. go mod tidy + make proto compiles the protos
4. LLM generates handler code with REAL business logic
   → given the proto, endpoint descriptions, and go-micro patterns
5. go build — does it compile?
6. If no: feed errors back to LLM, get fixed code (up to 3 attempts)
7. If yes: service is ready

The handler prompt instructs the LLM to:
- Use sync.RWMutex for thread-safe in-memory state
- Include validation, edge cases, meaningful errors
- Write doc comments with @example tags for MCP
- Implement actual domain logic, not just map operations

Proto generation still uses deterministic templates (CRUD +
custom endpoints from the design spec) to guarantee correctness.
The compile-fix loop catches LLM mistakes automatically.

Both micro new --prompt and micro run --prompt use this flow.

* fix: handle edge cases in prompt-based generation

- Fix PATH for protoc-gen-micro in child processes
- Handle existing directories: skip structural files (main.go,
  go.mod, Makefile) if dir exists, always regenerate proto,
  only write placeholder handler if none exists
- Allow re-running micro new --prompt on same directory to
  iterate on business logic without clobbering user edits

Tested end-to-end: "a simple todo list with tasks and categories"
generates 2 services (task-service, category-service) with real
business logic (validation, toggle complete, etc.), compiles
after 1 fix iteration, and runs with 6 MCP tools discovered.

* feat: auto-detect modified handlers on regeneration

Instead of requiring a --keep-handlers flag, the generate package now
tracks a SHA-256 hash of each generated handler in a .micro metadata
file. On re-run, if the user has edited the handler since generation,
it's left untouched. Unmodified handlers are regenerated normally.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: add tests, fix go.mod, gitignore, proto tracking, spinner

- Add 12 tests covering helpers, proto generation, hash tracking
- Fix go.mod: write minimal module file, let go mod tidy resolve deps
- Add .gitignore to prompt-generated services
- Protect user-edited proto files (same hash tracking as handlers)
- Add spinner during LLM calls so it doesn't look hung

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: signal handling, existing service discovery, help text

- Ctrl+C during generation now cancels LLM calls immediately via
  signal-aware context; re-run picks up where it left off
- Design() scans for existing services in the working directory and
  includes their proto definitions in the prompt, so the LLM extends
  the system rather than redesigning from scratch
- Updated --prompt help text with usage examples on both new and run
- Listed all supported providers in flag descriptions
- Added discoverExisting test

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: show endpoints in run --prompt output, add micro chat hint

Print endpoint names and descriptions when designing services so users
see what was built. Add a micro chat hint to the run banner so users
know how to interact with their services after startup.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: generated go.mod uses go 1.24 with explicit go-micro require

go 1.22 with no explicit require caused Go to resolve sub-packages
(gateway/mcp, client, server) as separate modules, hitting stale v1.18
tags. Pin to go 1.24 + require go-micro.dev/v5 v5.24.0 so go mod tidy
resolves all sub-packages from the root module correctly.

Tested end-to-end: 4 services generated and compiled successfully.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: skip handler regeneration when proto unchanged

Compare proto hash before and after structure generation. If the proto
didn't change and the handler wasn't edited by the user, skip go mod
tidy, make proto, LLM handler generation, and compile-fix entirely.
Prints "(unchanged)" instead.

Reduces re-run of 4-service project from ~2 minutes to ~10 seconds.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: confirm design before generating code

Show the service design (names, endpoints) and prompt "Generate? [Y/n]"
before spending LLM time on handler generation. Applies to both
micro new --prompt and micro run --prompt. Default is yes (enter).

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: use port :0 for MCP in generated multi-service projects

Each generated service had mcp.WithMCP(":3001") hardcoded, causing
port conflicts when running multiple services. Use :0 to auto-assign
a free port. micro run's central gateway handles unified MCP access.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: truncation detection, tool result display in chat

- Detect truncated LLM responses (unbalanced braces, doesn't end
  with '}') and retry with a conciseness hint before falling through
  to compile-fix
- Show tool call results in micro chat output (← for success, ✗ for
  errors) so users can see what the LLM did
- Add Result/Error fields to ToolCall, populated by Anthropic provider
  after tool execution
- Add isTruncated tests

Tested end-to-end with Anthropic: services generate, compile, start,
register, respond to RPC calls, and micro chat discovers and calls
tools correctly.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: Anthropic tool loop, service naming, chat tool results

Anthropic provider:
- Fix tool execution loop to properly iterate (was re-processing all
  tool calls instead of only new ones each round)
- Clean assistant content blocks before sending back (strip 'id' from
  text blocks that Anthropic rejects on input)
- Include tools in follow-up requests so model can make additional calls
- Loop up to 10 rounds until model responds with text only

Service naming:
- Strip '-service' suffix from micro.New() name so services register
  as 'task', 'category' instead of 'taskservice', 'categoryservice'

Chat:
- Show tool results (← for success) and errors (✗) in chat output

Tested end-to-end: create task → list tasks works as multi-step
orchestration through micro chat with Anthropic Claude.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: blog post 13 — from prompt to production

Covers the full micro run --prompt flow: design, generate, compile-fix,
run, and chat orchestration. Positions agent-as-orchestrator as the
answer to service coordination.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: timeouts, max_tokens, TTY detection, smaller services

- Add 60s timeout on design, 90s on handler generation, 60s on
  compile-fix LLM calls so hung providers don't block forever
- Bump Anthropic max_tokens from 4096 to 8192 to reduce truncation
- Add TTY detection: spinner prints static message in non-TTY (CI/pipes)
  instead of ANSI escape codes
- Tighten prompts: max 200 lines per handler, 2-4 services, 5-8 fields,
  explicit "services don't call each other" rule

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: chat suggests creating services when capabilities are missing

Update system prompt with the list of available services. When the user
asks for something no existing service can handle, the agent explains
what's available and suggests the exact micro new --prompt command to
create the missing service.

This is the natural evolution path: start with a few services, talk to
them via chat, and when the domain grows, the agent tells you what to
add. Each service stays small and focused.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: chat generates and starts services inline, drop -service suffix

Chat agent now has a micro_generate_service tool. When the user asks
for a capability that doesn't exist, the agent generates the service,
compiles it, starts it as a background process, waits for registration,
re-discovers tools, and uses the new endpoints immediately — all within
the conversation.

Service naming: design prompt now instructs LLM to return names without
'-service' suffix (e.g. 'task' not 'task-service'). buildMain keeps
TrimSuffix as safety net for backward compatibility.

Spawned processes are cleaned up when chat exits.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: rewrite blog post 13 with inline service generation

Updated to reflect the full UX: services generate and start within
the chat conversation. Added the shipping example showing the agent
creating a service mid-conversation. Removed -service suffix from
all examples. Tightened the narrative around agent-as-orchestrator.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: persistent storage, README quickstart, auto-detect new services

Storage: generated handlers now use go-micro's store package instead
of in-memory maps. Data persists across restarts. The handler prompt
includes store API examples so the LLM generates correct store usage.

README: added "Generate From a Prompt" section with micro run --prompt
and micro chat examples, linking to blog post 13.

Watcher: micro run now scans for new service directories every 5s. When
micro chat generates a service, micro run detects the new directory,
builds it, starts it, and adds it to the watcher — fully automatic.
Added AddDir/Dirs methods to the watcher.

Blog: updated post 13 with persistent storage example and watcher note.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-03 20:31:01 +01:00
2026-02-04 14:12:59 +00:00
2026-02-11 11:46:02 +00:00
2026-02-04 14:37:40 +00:00
2025-05-04 21:48:02 +01:00
2026-02-04 14:37:40 +00:00
2026-02-04 14:37:40 +00:00
2026-02-04 14:37:40 +00:00
2026-02-04 14:37:40 +00:00
2026-02-04 14:01:16 +00:00
2026-02-04 14:12:59 +00:00
v5
2024-06-04 21:40:43 +01:00
2024-07-07 08:04:29 +01:00
2023-03-20 16:48:44 +00:00
2026-02-04 14:12:59 +00:00

Go Micro Go.Dev reference Go Report Card

Go Micro is a framework for distributed systems development.

Sponsors


Overview

Go Micro microservices architecture

Go Micro provides the core requirements for distributed systems development including RPC and Event driven communication. The Go Micro philosophy is sane defaults with a pluggable architecture. We provide defaults to get you started quickly but everything can be easily swapped out.

Features

Go Micro abstracts away the details of distributed systems. Here are the main features.

  • Authentication - Auth is built in as a first class citizen. Authentication and authorization enable secure zero trust networking by providing every service an identity and certificates. This additionally includes rule based access control.

  • Dynamic Config - Load and hot reload dynamic config from anywhere. The config interface provides a way to load application level config from any source such as env vars, file, etcd. You can merge the sources and even define fallbacks.

  • Data Storage - A simple data store interface to read, write and delete records. It includes support for many storage backends in the plugins repo. State and persistence becomes a core requirement beyond prototyping and Micro looks to build that into the framework.

  • Data Model - A typed data model layer with CRUD operations, queries, and multiple backends (memory, SQLite, Postgres). Define Go structs with tags and get type-safe Create/Read/Update/Delete/List/Count operations. Accessible via service.Model() alongside service.Client() and service.Server() for a complete service experience: call services, handle requests, save and query data.

  • Service Discovery - Automatic service registration and name resolution. Service discovery is at the core of micro service development. When service A needs to speak to service B it needs the location of that service. The default discovery mechanism is multicast DNS (mdns), a zeroconf system.

  • Load Balancing - Client side load balancing built on service discovery. Once we have the addresses of any number of instances of a service we now need a way to decide which node to route to. We use random hashed load balancing to provide even distribution across the services and retry a different node if there's a problem.

  • Message Encoding - Dynamic message encoding based on content-type. The client and server will use codecs along with content-type to seamlessly encode and decode Go types for you. Any variety of messages could be encoded and sent from different clients. The client and server handle this by default. This includes protobuf and json by default.

  • RPC Client/Server - RPC based request/response with support for bidirectional streaming. We provide an abstraction for synchronous communication. A request made to a service will be automatically resolved, load balanced, dialled and streamed.

  • Async Messaging - PubSub is built in as a first class citizen for asynchronous communication and event driven architectures. Event notifications are a core pattern in micro service development. The default messaging system is a HTTP event message broker.

  • MCP Integration - An MCP gateway you can integrate as a library, server or CLI command which automatically exposes services as tools for agents or other AI applications. Every service/endpoint get's converted into a callable tool.

  • Multi-Service Binaries - Run multiple services in a single process with isolated state per service. Start as a modular monolith, split into separate deployments when you need independent scaling. Each service gets its own server, client, and store while sharing the registry and broker for inter-service communication.

  • Pluggable Interfaces - Go Micro makes use of Go interfaces for each distributed system abstraction. Because of this these interfaces are pluggable and allows Go Micro to be runtime agnostic. You can plugin any underlying technology.

Getting Started

To make use of Go Micro

go get go-micro.dev/v5@v5.16.0

Create a service and register a handler

package main

import (
        "go-micro.dev/v5"
)

type Request struct {
        Name string `json:"name"`
}

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

type Say struct{}

func (h *Say) Hello(ctx context.Context, req *Request, rsp *Response) error {
        rsp.Message = "Hello " + req.Name
        return nil
}

func main() {
        // create the service
        service := micro.New("helloworld")

        // register handler
        service.Handle(new(Say))

        // run the service
        service.Run()
}

Set a fixed address

service := micro.New("helloworld", micro.Address(":8080"))

Call it via curl

curl -XPOST \
     -H 'Content-Type: application/json' \
     -H 'Micro-Endpoint: Say.Hello' \
     -d '{"name": "alice"}' \
      http://localhost:8080

MCP & AI Agents

AI agent calling microservices via MCP

Go Micro is designed for an agent-first workflow. Every service you build automatically becomes a tool that AI agents can discover and use via the Model Context Protocol (MCP).

Services as Tools

Write a normal Go Micro service and it's instantly available as an MCP tool:

// SayHello greets a person by name.
// @example {"name": "Alice"}
func (g *GreeterService) SayHello(ctx context.Context, req *HelloRequest, rsp *HelloResponse) error {
    rsp.Message = "Hello " + req.Name
    return nil
}

Run with micro run and the agent playground and MCP tools registry are ready:

micro run
# Agent Playground:  http://localhost:8080/agent
# MCP Tools:         http://localhost:8080/mcp/tools

Use micro mcp serve for local AI tools like Claude Code, or connect any MCP-compatible agent to the HTTP endpoint.

micro chat

For an interactive terminal session that lets you talk to your services through an LLM:

ANTHROPIC_API_KEY=sk-ant-... micro chat --provider anthropic
> list all users
> create an order for product 42

micro chat discovers every service in the registry, exposes each endpoint as a tool, and lets the model orchestrate calls. The same building blocks (ai.Tools) work from your own services:


tools := ai.NewTools(service.Registry())
discovered, _ := tools.Discover()

m := ai.New("anthropic",
    ai.WithAPIKey(key),
    ai.WithTools(tools),
)
resp, _ := m.Generate(ctx, &ai.Request{
    Prompt: userInput,
    Tools:  discovered,
})

See the MCP guide for authentication, scopes, and advanced usage.

Multi-Service Binaries

Run multiple services in a single binary — start as a modular monolith, split into separate deployments later when you actually need to.

users := micro.New("users", micro.Address(":9001"))
orders := micro.New("orders", micro.Address(":9002"))

users.Handle(new(Users))
orders.Handle(new(Orders))

// Run all services together with shared lifecycle
g := micro.NewGroup(users, orders)
g.Run()

Each service gets its own server, client, store, and cache while sharing the registry, broker, and transport — so they can discover and call each other within the same process.

See the multi-service example for a working demo.

Data Model

Go Micro includes a typed data model layer for persistence. Define a struct, tag a key field, and get type-safe CRUD and query operations backed by memory, SQLite, or Postgres.

import (
        "go-micro.dev/v5/model"
        "go-micro.dev/v5/model/sqlite"
)

// Define your data type
type User struct {
        ID    string `json:"id" model:"key"`
        Name  string `json:"name"`
        Email string `json:"email" model:"index"`
        Age   int    `json:"age"`
}

Register your types and use the model:

service := micro.New("users")

// Register and use the service's model backend
db := service.Model()
db.Register(&User{})

// CRUD operations
db.Create(ctx, &User{ID: "1", Name: "Alice", Email: "alice@example.com", Age: 30})

user := &User{}
db.Read(ctx, "1", user)

user.Name = "Alice Smith"
db.Update(ctx, user)

db.Delete(ctx, "1", &User{})

Query with filters, ordering, and pagination:

var results []*User

// Find users by field
db.List(ctx, &results, model.Where("email", "alice@example.com"))

// Complex queries
db.List(ctx, &results,
        model.WhereOp("age", ">=", 18),
        model.OrderDesc("name"),
        model.Limit(10),
        model.Offset(20),
)

count, _ := users.Count(ctx, model.Where("age", 30))

Swap backends with an option:

// Development: in-memory (default)
service := micro.New("users")

// Production: SQLite or Postgres
db, _ := sqlite.New(model.WithDSN("file:app.db"))
service := micro.New("users", micro.Model(db))

Every service gets Client(), Server(), and Model() — call services, handle requests, and save data all from the same interface.

Examples

Check out /examples for runnable code:

See all examples for more.

Protobuf

Install the code generator and see usage in the docs:

go install go-micro.dev/v5/cmd/protoc-gen-micro@v5.16.0

Note: Use a specific version instead of @latest to avoid module path conflicts. See releases for the latest version.

Docs: internal/website/docs/getting-started.md

Command Line

Install the CLI:

go install go-micro.dev/v5/cmd/micro@v5.16.0

Note: Use a specific version instead of @latest to avoid module path conflicts. See releases for the latest version.

Quick Start

micro new helloworld              # Create a new service
cd helloworld
micro run                          # Run with API gateway and hot reload

Then open http://localhost:8080 to see your service and call it from the browser.

Generate From a Prompt

Describe what you need in plain English. The AI designs services, writes handlers with real business logic, compiles them, and starts them:

micro run --prompt "a task management system with categories" --provider anthropic

Then talk to your services through an agent:

micro chat --provider anthropic
> Create a Work category, then add a task called 'Finish report' to it

The agent orchestrates across services automatically. When you need a capability that doesn't exist, the agent generates a new service mid-conversation. Read more.

Development Workflow

Stage Command Purpose
Create micro new myservice Scaffold a service (--template crud/pubsub/api)
Develop micro run Dev mode with hot reload and API gateway
Test micro call Call a service endpoint from the CLI
Chat micro chat Talk to your services through an LLM
Gateway micro api Standalone HTTP-to-RPC gateway
Build micro build Compile production binaries
Deploy micro deploy Push to a remote Linux server via SSH + systemd
Dashboard micro server Production web UI with auth

Inspecting the Framework

Every core interface has a matching command — inspect the registry, broker, store, and config from the terminal:

micro registry list                  # list services
micro broker subscribe events        # stream a topic
micro broker publish events 'hello'  # publish a message
micro store write greeting hello     # write a record
micro store read greeting            # read it back
micro config get database.host       # read config (from DATABASE_HOST)

These mirror the registry, broker, store, and config packages.

micro run

micro run starts your services with:

  • Web Dashboard - Browse and call services at /
  • Agent Playground - AI chat with MCP tools at /agent
  • API Explorer - Browse endpoints and schemas at /api
  • API Gateway - HTTP to RPC proxy at /api/{service}/{method} (no auth in dev mode)
  • MCP Tools - Services as AI tools at /mcp/tools
  • Health Checks - Aggregated health at /health
  • Hot Reload - Auto-rebuild on file changes

Note: micro run and micro server use a unified gateway architecture. See Gateway Architecture for details.

micro run                    # Gateway on :8080
micro run --address :3000    # Custom gateway port
micro run --no-gateway       # Services only
micro run --env production   # Use production environment

Configuration

For multi-service projects, create a micro.mu file:

service users
    path ./users
    port 8081

service posts
    path ./posts
    port 8082
    depends users

env development
    DATABASE_URL sqlite://./dev.db

The gateway runs on :8080 by default, so services should use other ports.

Deployment

Deploy to any Linux server with systemd:

# On your server (one-time setup)
curl -fsSL https://go-micro.dev/install.sh | sh
sudo micro init --server

# From your laptop
micro deploy user@your-server

The deploy command:

  1. Builds binaries for Linux
  2. Copies via SSH to the server
  3. Sets up systemd services
  4. Verifies services are healthy

Optionally run micro server on the deployed machine for a production web dashboard with JWT auth, user management, and API explorer.

Manage deployed services:

micro status --remote user@server    # Check status
micro logs --remote user@server      # View logs
micro logs myservice --remote user@server -f  # Follow specific service

No Docker required. No Kubernetes. Just systemd.

See internal/website/docs/deployment.md for full deployment guide.

See cmd/micro/README.md for full CLI documentation.

Docs: internal/website/docs

Package reference: https://pkg.go.dev/go-micro.dev/v5

User Guides:

Architecture & Performance:

Security:

Supported AI Providers

Go Micro’s ai package gives every provider the same interface: Init, Generate, Stream, and functional options. Swap providers with a single import.

Provider Import Default Model
Anthropic go-micro.dev/v5/ai/anthropic claude-sonnet-4-20250514
Google Gemini go-micro.dev/v5/ai/gemini gemini-2.5-flash
Groq go-micro.dev/v5/ai/groq llama-3.3-70b-versatile
Mistral go-micro.dev/v5/ai/mistral mistral-large-latest
OpenAI go-micro.dev/v5/ai/openai gpt-4o
Together AI go-micro.dev/v5/ai/together Llama-3.3-70B-Instruct-Turbo
Atlas Cloud go-micro.dev/v5/ai/atlascloud llama-3.3-70b

Any provider that exposes an OpenAI-compatible API can also be used directly:

m := ai.New("openai",
    ai.WithAPIKey("your-key"),
    ai.WithBaseURL("https://api.yourprovider.com"),
)

Want to add your platform? See the AI Provider Integration Guide for how to implement ai.Model and submit a PR. We welcome both code contributions and sponsorships from AI infrastructure companies — reach out via a GitHub issue.

Adopters

  • Sourse - Work in the field of earth observation, including embedded Kubernetes running onboard aircraft, and we’ve built a mission management SaaS platform using Go Micro.