Compare commits

..

266 Commits

Author SHA1 Message Date
Codex c70fa679c0 Harden provider conformance selection
Harness (E2E) / Harnesses (mock LLM) (push) Waiting to run
Harness (E2E) / Provider harnesses (live LLM, if keys present) (push) Waiting to run
Lint / golangci-lint (push) Waiting to run
Run Tests / Unit Tests (push) Waiting to run
Run Tests / Etcd Integration Tests (push) Waiting to run
2026-06-25 08:14:19 +00:00
Asim Aslam b45c94e201 ci: instruct Codex to open the PR via gh, not the make_pr stub (#3059)
Codex's make_pr tool in the Cloud sandbox is a no-op stub — it records the
PR title/body and returns them "for downstream consumption" (the manual
"Create PR" click), but never pushes a branch or calls the GitHub API. That
is why "make_pr called, nothing happened": the tool literally cannot open a
PR. With the gh CLI now installed in the Codex setup and origin pointed at
the repo, the dispatch tells Codex to push and open the PR itself
(git push + gh pr create) instead of relying on make_pr.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-25 08:02:23 +01:00
Asim Aslam 23051459d8 docs: require Codex PR creation step (#3058) 2026-06-25 07:35:06 +01:00
Asim Aslam 4c7e6e96eb agent: correlate run timelines with traces (#3057) 2026-06-25 07:20:11 +01:00
Asim Aslam ef21ac6494 Add JSON output for agent run inspection (#3055) 2026-06-25 06:51:06 +01:00
Asim Aslam 53193fbbe7 agent: mark successful run timelines complete (#3054) 2026-06-25 06:50:51 +01:00
Asim Aslam 105cc9d2fb Add flow retry backoff (#3053) 2026-06-25 06:50:36 +01:00
Asim Aslam d369cf290c Improve agent run index summaries (#3049) 2026-06-25 01:31:08 +01:00
Asim Aslam 949542fa65 flow: add pending run resume helper (#3048) 2026-06-25 01:30:29 +01:00
Asim Aslam 1421ccbea6 Improve flow run inspection (#3047) 2026-06-25 01:30:01 +01:00
Asim Aslam 7a0ca65b68 Expose agent run IDs on responses (#3044) 2026-06-24 23:10:45 +01:00
Asim Aslam 28433f2db8 docs: align continuous improvement scheduler notes (#3043) 2026-06-24 23:09:49 +01:00
Asim Aslam cb61ccb9d7 Make flow checkpoint listing deterministic (#3040) 2026-06-24 21:51:18 +01:00
Asim Aslam fbb5fd46ae ci: open a fresh issue per increment so Codex opens a new PR each run (#3039)
Codex derives its PR branch name from the triggering issue's context, so
re-commenting on a single tracker issue (#3024) every hour collapsed every
increment onto one branch name. The first increment opened a PR; the rest
collided on the occupied branch and silently failed to open one — which is
why repeated runs produced "make_pr called, nothing happened."

Open a unique issue per run and dispatch Codex there, so each increment gets
its own branch and a clean PR. The dispatch asks Codex to "Closes #<issue>"
so each tracking issue auto-closes when its PR merges. The explicit
branch-name request (which Codex ignored in favor of the issue-derived name)
is dropped.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 21:46:44 +01:00
Asim Aslam ff6af5d46b Make agent run timelines deterministic (#3038) 2026-06-24 20:42:38 +01:00
Asim Aslam 89ae0a10eb website: h1 → "An Agent Harness for Go" (#3037)
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 20:29:41 +01:00
Asim Aslam 666e1f765e ci: give each Codex dispatch a unique branch to avoid collisions (#3036)
* fix: harden flow step execution against nil Run and cancellation

A step with no Run function panicked the run; it now returns a clear
configuration error. The retry loop also kept retrying after the run's
context was canceled or its deadline passed — it now stops immediately
and surfaces the context error, preserving cancellation/deadline
semantics for durable workflow runs. Adds regression coverage for both.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* ci: give each Codex dispatch a unique branch to avoid collisions

Codex derives its PR branch name from the dispatch text. The hourly loop
posted an identical generic prompt every run, so every increment resolved
to the same branch name — the previous increment's branch (until auto-
merged and deleted) blocked the next PR from opening. Include the run
number in the prompt and explicitly request a fresh
codex/improvement-<run_number> branch, so each increment is isolated.
auto-merge-codex.yml still matches (codex/* prefix) and deletes on merge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 20:26:29 +01:00
Asim Aslam 5a0df7991e fix: harden flow step execution against nil Run and cancellation (#3034)
A step with no Run function panicked the run; it now returns a clear
configuration error. The retry loop also kept retrying after the run's
context was canceled or its deadline passed — it now stops immediately
and surfaces the context error, preserving cancellation/deadline
semantics for durable workflow runs. Adds regression coverage for both.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 18:49:32 +01:00
Asim Aslam 631c58cb75 ci: gate Codex dispatch on CODEX_TRIGGER_TOKEN secret (#3033)
goreleaser / goreleaser (push) Waiting to run
* thesis: position Go Micro as complementary to LangChain, not competing

Add a 'Where we fit' section: 'harness' has two layers — the intra-agent
harness (single-model runtime: prompts, tools, context, sandbox, the Ralph
loop) that LangChain/LangGraph/deepagents/Claude Code own and we do NOT
compete with, and the operational harness (the distributed substrate agents
operate inside: services-as-tools, discovery, durable runs, observability,
interop, the services->agents->workflows lifecycle) which is our focus. They
stack and interoperate via MCP/A2A; we make those agents better neighbours,
not obsolete.

* ci: gate Codex dispatch on CODEX_TRIGGER_TOKEN secret

Codex ignores @codex comments authored by the github-actions bot, so the
hourly dispatch was producing no PRs while still posting to the tracker
issue. Gate the comment step on the presence of CODEX_TRIGGER_TOKEN: the
workflow now no-ops until a PAT for a Codex-followed account is set, then
activates automatically with no further change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 17:39:44 +01:00
Asim Aslam 57e83ca9a0 thesis: position Go Micro as complementary to LangChain, not competing (#3032)
Add a 'Where we fit' section: 'harness' has two layers — the intra-agent
harness (single-model runtime: prompts, tools, context, sandbox, the Ralph
loop) that LangChain/LangGraph/deepagents/Claude Code own and we do NOT
compete with, and the operational harness (the distributed substrate agents
operate inside: services-as-tools, discovery, durable runs, observability,
interop, the services->agents->workflows lifecycle) which is our focus. They
stack and interoperate via MCP/A2A; we make those agents better neighbours,
not obsolete.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 15:54:56 +01:00
Asim Aslam 8d59779465 website: fix mobile horizontal overflow on the landing page (#3031)
Grid items defaulted to min-width:auto, so the wide <pre> blocks (install
command, the 'micro run' sample) forced their row past the viewport —
clipped by overflow-x:hidden, so no scroll but not fitting either. Let
grid items shrink (.two-col > * { min-width:0 }) and wrap the code blocks
on mobile (white-space:pre-wrap; overflow-wrap:anywhere) so every section
fits the screen with no overflow or scroll.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 15:48:35 +01:00
Asim Aslam 3d0c5237f0 docs: burger (☰) sidebar toggle on the left on mobile (#3030)
Replace the docs header 'Menu' button with a ☰ burger icon and move it to the
left next to the wordmark (where the logo used to be), grouped in a .nav-left
container. Keeps id=menuToggle so the existing sidebar-toggle JS still works;
desktop is unchanged (toggle hidden).

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 15:31:52 +01:00
Asim Aslam cf1f42d15b website: text-only 'Go Micro' brand, drop the nav logo (#3029)
Remove the logo image from the nav-brand in the marketing nav include and the
docs and blog layouts; the brand is now just the 'Go Micro' wordmark.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 15:27:47 +01:00
Asim Aslam 728ea5eae7 loop: add the thesis / North Star and make the loop align to it (#3028)
Add internal/docs/THESIS.md — the vision the autonomous loop steers by: a
holistic agent harness AND service framework encapsulating the lifecycle of
services -> agents -> workflows (workloads come after agents; the value is in
composing it into systems that do real work, on schedules and in loops).

Wire it in as the alignment criterion: the continuous-improvement charter and
the Codex dispatch prompt now require every increment to advance the North Star,
so improvements compound toward the thesis instead of drifting locally.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 15:23:01 +01:00
Asim Aslam 5e9accfd45 Add agent OpenTelemetry run observability (#3027) 2026-06-24 14:57:25 +01:00
Asim Aslam 0adb4f0aac loop: hourly Codex dispatch + auto-merge green Codex PRs (#3026)
- continuous-improvement: cadence 12h -> hourly.
- add auto-merge-codex workflow: every 15 min, merge open PRs that are
  codex-labelled AND from a codex/* branch once all checks are green
  (gh pr checks). CI (build/test/lint/harnesses) is the only gate — no
  human involvement. Scoped tightly so nothing else auto-merges.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 14:26:31 +01:00
Asim Aslam ee44926191 loop: drive the scheduled backbone via Codex, not an Anthropic key (#3025)
A Claude Max subscription exposes no API key for CI, and Atlas Cloud models
can't run a coding agent — so the durable scheduler triggers Codex instead:
on a cadence it posts an @codex instruction on the tracker issue (#3024) to
run one improvement increment. Prefers a CODEX_TRIGGER_TOKEN PAT if set
(in case Codex ignores the Actions bot), else the default token.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 14:15:41 +01:00
Asim Aslam 09cf00b5ec docs: mark harness Resilience as shipped (#3023)
* loop: establish the continuous-improvement charter + scheduled backbone

Define the autonomous improvement loop (internal/docs/CONTINUOUS_IMPROVEMENT.md):
full autonomy with correctness (build/test/lint) as the only gate, work sourced
from roadmap + issues + an improvement radar + dogfooding, Claude Code driving
and Codex executing scoped tasks, with brand/positioning and breaking API kept
with the human.

Add a durable scheduled GitHub Action (.github/workflows/continuous-improvement.yml)
as the session-independent backbone — a safe no-op until an ANTHROPIC_API_KEY
secret is added.

* docs: mark harness Resilience as shipped

Resilience (per-call timeout + context propagation + opt-in retry/backoff)
landed in #3017/#3021; update the agent-harness status table from
'In progress' to 'Shipped'.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 13:58:02 +01:00
Asim Aslam da5fa1f27c loop: establish the continuous-improvement charter + scheduled backbone (#3022)
Define the autonomous improvement loop (internal/docs/CONTINUOUS_IMPROVEMENT.md):
full autonomy with correctness (build/test/lint) as the only gate, work sourced
from roadmap + issues + an improvement radar + dogfooding, Claude Code driving
and Codex executing scoped tasks, with brand/positioning and breaking API kept
with the human.

Add a durable scheduled GitHub Action (.github/workflows/continuous-improvement.yml)
as the session-independent backbone — a safe no-op until an ANTHROPIC_API_KEY
secret is added.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 13:56:38 +01:00
Asim Aslam a8ea60120e agent: make model retries opt-in and harden retry backoff (#3021)
Follow-up to #3017. A Generate runs the whole tool-execution turn, so
auto-retrying it re-runs already-executed (possibly side-effecting) tool
calls. Default ModelMaxAttempts 3 -> 1: retries are now opt-in via
ModelRetry. The timeout stays as a safety net.

Also harden ai.GenerateWithRetry: always back off between retries
(exponential, capped at 30s, default 200ms if unset) so an opt-in retry
can't busy-loop the provider even with Backoff=0.

Verified: go build, go test -race ./agent/... ./ai/, golangci-lint.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 12:42:15 +01:00
Asim Aslam d7050e9cc2 website: size hero image to 600px (#3020)
Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 12:39:22 +01:00
Asim Aslam 536806119e website: tighten hero — drop 'in Go', simpler tagline, image in-hero at 800px (#3019)
- h1: 'An Agent Harness and Service Framework' (drop 'in Go')
- tagline: 'Build agents, services, and workflows on one runtime'
- move the hero image into the hero block (between tagline and the install
  line), capped at 800px to fit the hero column, and remove the separate
  full-width image section

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 12:33:58 +01:00
Asim Aslam ab2c092693 Add agent model retry and timeout resilience (#3017) 2026-06-24 12:30:58 +01:00
Asim Aslam 7144cddc00 website: new hero image + reframe landing as harness AND service framework (#3018)
- Regenerate the hero image (text-free, via the framework's own Atlas Cloud
  image model) — an agent orchestrating service nodes. The old one had baked-in
  'AI native microservices framework' text that contradicts the positioning;
  text-free so copy changes can't invalidate it again.
- h1 -> 'An Agent Harness and Service Framework in Go' (both, not harness-only).
- Tagline reframed around agents, services, and flows on one runtime.
- Drop the 'moved from a service framework to an agent harness' line — it's
  additive (both in one), not a pivot away from services.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 12:27:09 +01:00
Asim Aslam 9f28cc4c86 docs: bake cross-agent coordination rules into CLAUDE.md and CODEX.md (#3016)
Add matching 'Coordination' sections so Claude Code and Codex self-coordinate:
lane/branch ownership (claude/* vs codex/*, never share a branch), base PRs
on master (don't stack on an in-flight branch — the #3007 orphan lesson),
one concern per PR, cross-review before merge, the @codex dispatch
conventions (review reserved, serial, fix-in-place), and CI as the gate.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 12:13:21 +01:00
Asim Aslam 8a19dc2d7c docs/blog: anchor the agent-harness positioning (#3015)
- Add the canonical concept doc 'The Agent Harness' (docs/guides/agent-harness.md)
  + nav entry: what the harness is, each piece mapped to a feature, honest
  about shipped vs in-progress.
- Add blog post /blog/30 'Go Micro is an Agent Harness' (the public articulation;
  precise about what ships today vs the Now/Next roadmap).
- Align the ROADMAP.md opening line to the agent-harness framing.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 11:59:42 +01:00
Asim Aslam daacd4830f harness/new: make conformance timeout honest and contract test cheaper (#3008)
Follow-up to #3006:

- provider-conformance: build each harness to a temp binary and run that
  instead of 'go run'. 'go run' launches the harness as a child it doesn't
  kill on context cancellation, so a timed-out harness (which starts local
  services) could be orphaned and outlive the run. Running the built binary
  makes the per-run timeout actually terminate the work.
- contract test: skip under -short, and use 'go build ./...' instead of
  'go test ./...' (the contract is that the generated service builds). This
  keeps the default unit-test suite from shelling out to the toolchain and
  the network on every run.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-24 11:48:40 +01:00
Asim Aslam 844ab4a14b Add provider-conformance harness, contract test, and reframe docs to 'agent harness' (#3006)
* docs: reposition go micro as agent harness

* ci: rename universe workflow to harness
2026-06-24 11:37:43 +01:00
Asim Aslam 156b051191 docs: fix service quickstart snippets (#3005) 2026-06-24 08:21:38 +01:00
Asim Aslam 21a6746d86 docs: add codex maintainer playbook (#3004) 2026-06-24 07:58:48 +01:00
Asim Aslam 2c04f61331 blog: announce OpenAI Codex for Open Source grant (/blog/29) (#3003)
Add a blog post for the OpenAI Codex for Open Source grant, list it on
the blog index, and repoint the OpenAI sponsor logo (README + landing) to
the post — matching how the Anthropic (/blog/3) and Atlas Cloud (/blog/8)
sponsor logos link to their posts.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-23 18:35:51 +01:00
Asim Aslam 634fc9bced sponsors: add OpenAI (Codex for Open Source) (#3002)
Go Micro received an OpenAI Codex for Open Source grant. Add the OpenAI
logo to the README and landing-page sponsors, alongside Anthropic and
Atlas Cloud.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-23 18:21:35 +01:00
Asim Aslam a503628ef1 flow: add Loop — run a step until done, with a guaranteed ceiling (#3001)
Adds the agentic 'loop' to flows: flow.Loop(body, opts...) is a StepFunc
that runs a body step repeatedly, carrying State across passes, until a
stop condition fires or a hard iteration cap is reached.

- Stop modes: flow.Until (code-defined predicate) and flow.UntilLLM (the
  model judges the goal met after each pass — the supervised 'Ralph'
  loop). Either firing stops the loop.
- flow.LoopMax is the guardrail: the body never runs more than n times, so
  the loop always terminates and can't run up an unbounded bill. Hitting
  the cap returns the latest state rather than erroring.
- flow.OnIteration reports per-pass progress.
- Composes as a normal flow step (checkpointed by the step engine).
- Exposed at the top level as micro.FlowLoop / FlowUntil / FlowUntilLLM /
  FlowLoopMax / FlowOnIteration, symmetric with the other Flow* helpers.

Includes tests, an offline runnable example (examples/flow-loop), an
'Agent Loops' guide, and a CHANGELOG entry.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-23 12:39:17 +01:00
Asim Aslam 3f40028a7f website: deduplicate header/footer via Jekyll includes (#3000)
Extract the nav and footer link lists into _includes/nav-links.html and
_includes/footer-links.html, and the full marketing nav/footer into
_includes/marketing-nav.html and _includes/marketing-footer.html.

- index.html and support.html now pull their nav/footer from the shared
  marketing includes (and gain Liquid front matter so includes resolve).
- The docs and blog layouts pull the same link lists, so a nav/footer
  link lives in exactly one place site-wide. This also adds the missing
  Support link to the blog nav and fixes the blog footer's Support link
  (it still pointed at the question template).
- Active nav state is driven by a per-page nav_active flag.

Verified with a local jekyll build: landing, support, docs, and blog
pages all render the shared nav/footer correctly.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-23 05:45:09 +01:00
Asim Aslam b9665ad196 website: add Support to top nav (landing + docs layout) (#2999)
* website: add Support to top nav (landing + docs layout)

Link /docs/support.html from the nav bar on the landing page and the
shared docs layout, and point the docs-layout footer Support link there
too (was the question issue template).

* website: add a dedicated marketing /support page

New top-level /support.html styled like the landing site (hero, tier
cards, community links, CTAs) — separate from the docs reference at
/docs/support.html. Repoint the site nav, footer, landing 'Commercial
support' button, and the FUNDING button to it.

* website: serve the support page at a clean /support URL

Add 'permalink: /support' to support.html (same mechanism the blog uses)
and point all nav/footer/CTA/FUNDING links at /support instead of
/support.html.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 22:42:10 +01:00
Asim Aslam 053103fb7f website: trim landing tagline and use 'workflows' (#2998)
Drop the 'Every service is an MCP tool; every agent speaks A2A' sentence
and use 'workflows' (clearer than 'flows') in the one-liner.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 19:54:35 +01:00
Asim Aslam 0ba2253357 website: trim landing tagline to the one-liner (#2997)
Drop the 'Every service is an MCP tool; every agent speaks A2A' sentence.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 19:52:05 +01:00
Asim Aslam 2339155ff2 Enforce blocking golangci-lint in CI and clear lint backlog (#2996)
goreleaser / goreleaser (push) Waiting to run
* lint: clear the golangci-lint backlog and enforce a blocking lint in CI

Fixes #2988. Brings 'golangci-lint run ./...' to zero issues (was ~373):

- errcheck: explicitly ignore fire-and-forget calls with '_ =' (and a small
  errcheck.exclude-functions list for response writes — json Encoder.Encode,
  http ResponseWriter.Write, fmt.Fprint*); genuine cases handled.
- unused: remove dead code (unexported decls and dead test helpers) and the
  imports they orphaned.
- staticcheck: ST1005 error strings, ST1016 receiver names, S1000/S1017/S1019/
  S1023 simplifications, SA4004/SA4006/SA4010 dead code, SA1021 net.IP.Equal,
  SA6002 (store *[]byte in sync.Pool).
- govet: fix a context leak (lostcancel) in internal/util/mdns and move
  t.Fatal/Fatalf out of goroutines (testinggoroutine) in tests.
- ineffassign, unconvert: mechanical fixes.

CI: the Lint workflow now runs a blocking full-tree 'golangci-lint run' on
pushes and PRs (dropped only-new-issues now that the tree is clean).

Verified: go build, go vet, test compilation, and unit tests for the
behaviourally-touched packages all pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* website: emit go-source meta for /vN paths

pkg.go.dev uses go-source to link to the right files and lines. The /vN
go-get response now returns go-source alongside go-import. Does not affect
go install resolution.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 19:48:09 +01:00
Asim Aslam 3e885308a0 lint: clear the golangci-lint backlog and enforce a blocking lint in CI (#2995)
Fixes #2988. Brings 'golangci-lint run ./...' to zero issues (was ~373):

- errcheck: explicitly ignore fire-and-forget calls with '_ =' (and a small
  errcheck.exclude-functions list for response writes — json Encoder.Encode,
  http ResponseWriter.Write, fmt.Fprint*); genuine cases handled.
- unused: remove dead code (unexported decls and dead test helpers) and the
  imports they orphaned.
- staticcheck: ST1005 error strings, ST1016 receiver names, S1000/S1017/S1019/
  S1023 simplifications, SA4004/SA4006/SA4010 dead code, SA1021 net.IP.Equal,
  SA6002 (store *[]byte in sync.Pool).
- govet: fix a context leak (lostcancel) in internal/util/mdns and move
  t.Fatal/Fatalf out of goroutines (testinggoroutine) in tests.
- ineffassign, unconvert: mechanical fixes.

CI: the Lint workflow now runs a blocking full-tree 'golangci-lint run' on
pushes and PRs (dropped only-new-issues now that the tree is clean).

Verified: go build, go vet, test compilation, and unit tests for the
behaviourally-touched packages all pass.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 18:51:30 +01:00
Asim Aslam 4311b73361 Enhance ADK vs Go Micro comparison and apply lint fixes (#2994)
* docs: compare Go Micro with Google ADK in the comparison guide

Adds a 'vs Agent Frameworks (Google ADK)' section: ADK builds an agent,
Go Micro builds the distributed system the agent lives in (agents are
services in the mesh). Covers the category difference, a feature table,
when to choose each, and MCP/A2A interoperability.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* docs: replace ADK comparison slogan with concrete explanation

State plainly what each tool provides (ADK builds an agent process; Go Micro
builds the surrounding service mesh) instead of marketing phrasing.

* lint: apply golangci-lint autofixes; exclude ST1003 and demo errcheck

Mechanical, behaviour-preserving fixes applied by 'golangci-lint run --fix':
gofmt, misspell (US spelling), usestdlibvars (http.Method*/Status*), unconvert,
and the auto-fixable staticcheck simplifications (QF*, S1017/S1019/S1023/S1039).

Config: exclude ST1003 (remaining offenders are exported API renames, e.g.
web.Id, which would break compatibility) and skip errcheck for examples/ and
internal/harness/ (demo code where fire-and-forget is intentional).

Build and test compilation verified.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* lint: WIP cleanup checkpoint (errcheck config + partial fixes)

Checkpoint of an in-progress golangci-lint cleanup (background pass). Builds
cleanly; lint is not yet zero. Follow-up commit will complete the cleanup and
switch CI to a blocking full-tree lint.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 17:21:47 +01:00
Asim Aslam c3542127dd Enhance comparison guide for Go Micro and Google ADK (#2993)
* docs: compare Go Micro with Google ADK in the comparison guide

Adds a 'vs Agent Frameworks (Google ADK)' section: ADK builds an agent,
Go Micro builds the distributed system the agent lives in (agents are
services in the mesh). Covers the category difference, a feature table,
when to choose each, and MCP/A2A interoperability.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* docs: replace ADK comparison slogan with concrete explanation

State plainly what each tool provides (ADK builds an agent process; Go Micro
builds the surrounding service mesh) instead of marketing phrasing.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 17:07:45 +01:00
Asim Aslam 06659032a9 docs: install the CLI with @v6 instead of @latest (#2991)
Plain 'go install go-micro.dev/v6/cmd/micro@latest' fails on the public
module proxy with a version-constraints conflict: the proxy has cached the
sub-paths go-micro.dev/v6/cmd and .../cmd/micro as standalone v0/v1 modules
(from old github.com/micro/go-micro tags, surfaced during an earlier vanity
meta bug), so @latest resolves to v1.18.0 with a mismatched module path.

A version-prefix query (@v6) sidesteps it: those cached sub-path modules
have no v6.x.x versions, so Go falls back to the go-micro.dev/v6 root
module and builds correctly. Verified against proxy.golang.org.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 16:39:04 +01:00
Asim Aslam 8cad95cc29 website: add commercial support to the landing page (#2990)
The Sponsors section now also points production users to commercial
support & consulting, and the footer Support link routes to the support
page (community + commercial) instead of the question issue template.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 15:50:23 +01:00
Asim Aslam 2cbd6264d7 support: advertise commercial support, consulting, and sponsorship (#2989)
* support: advertise commercial support, consulting, and sponsorship

Adds a clear path to fund the project and pay for help, surfaced where
people look:
- SUPPORT.md + website /docs/support.html with a tier ladder (community,
  sponsor, support retainer, consulting)
- Commercial Support / Consulting issue template (the GitHub inbound funnel)
  and an issue-chooser config linking Sponsors and docs
- FUNDING.yml custom link to the support page; README section + nav entry

Community support stays free via issues; paid support and consulting are
scoped per engagement.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* ci: migrate golangci-lint to v2 config and enforce in CI (#2988)

- Rewrite .golangci.yaml for the v2 schema: start from the standard linter
  set (errcheck, govet, ineffassign, staticcheck, unused) plus bodyclose,
  misspell, unconvert, usestdlibvars. Sensible exclusions: generated code,
  built-in presets, looser tests, SA1019 deprecations (coordinated migration
  is separate), and the ported protoc-gen-micro generator for unused.
- Add a Lint workflow running golangci/golangci-lint-action with
  only-new-issues, so linting is enforced on new/changed code without a
  flag-day cleanup of the existing backlog.

The pre-existing backlog (errcheck/unused/naming and a few real bugs the
linter surfaces) is left for a dedicated follow-up so it can be reviewed on
its own rather than buried in this wiring change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 14:39:28 +01:00
Asim Aslam aa7cd6dc3b Enhance support agent example and fix protoless service scaffolding (#2986)
goreleaser / goreleaser (push) Waiting to run
* examples: support desk agent + blog walkthrough

A real-world, runnable example (examples/support): customers/tickets/notify
services become the agent's tools, a flow turns a ticket.created event into
the agent's work, and an approval gate guards the one action that touches a
customer. Runs with no API key (mock model) or against a live provider.

Adds blog/28 'Building a Support Agent in Go' and indexes both.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* fix(new): protoless services by default; fix @latest install (#2985)

micro new now scaffolds a reflection-based service by default — plain Go
types registered via service.Handle, no .proto, no Makefile proto target.
The generated project builds and runs with 'go run .' and zero external
tooling. Protocol Buffers move behind --proto (the crud/pubsub/api
templates imply it). When the proto workflow is used and protoc /
protoc-gen-go / protoc-gen-micro are missing, print exact install
instructions instead of failing with a cryptic plugin error.

Also fixes the 'go install go-micro.dev/v6/cmd/micro@latest' version
constraint conflict: the vanity go-import meta still advertised /v5, so Go
fell back to the bare module and resolved an ancient v1.x tag. Advertise
/v6 (keeping /v5 for existing users) and add a version-pin fallback note to
the install docs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* fix(new,install): pin generated go.mod to current go-micro; lead install with prebuilt binary (#2985)

- micro new now requires the exact go-micro version the CLI was built from
  (via build info), falling back to 'latest' for dev builds. An explicit
  require is also more robust than a bare import: 'go mod tidy' reliably
  resolves it, where a requireless go.mod could fail vanity discovery.
- Make the precompiled binary (curl install.sh) the recommended install in
  the docs; demote 'go install' to a from-source option with the version-pin
  fallback note.
- Sync the stale internal/scripts/install.sh to the working website script
  (it expected an old micro-OS-ARCH asset name; releases ship
  micro_OS_ARCH.tar.gz).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

* website: add corrected nginx vanity-import config (#2985)

The live go-micro.dev handler echoed the full request path into the
go-import prefix ($host$1), so go install go-micro.dev/v6/cmd/micro@latest
got prefix go-micro.dev/v6/cmd/micro — a package, not the module root — and
Go fell back to the ancient v1.x tags (version constraints conflict).

Add a dedicated /vN location that emits the module root (go-micro.dev/vN)
for any sub-path, and make the catch-all advertise the current module roots
instead of echoing arbitrary paths.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 10:22:25 +01:00
Asim Aslam 456ff18176 examples: support desk agent + blog walkthrough (#2984)
A real-world, runnable example (examples/support): customers/tickets/notify
services become the agent's tools, a flow turns a ticket.created event into
the agent's work, and an approval gate guards the one action that touches a
customer. Runs with no API key (mock model) or against a live provider.

Adds blog/28 'Building a Support Agent in Go' and indexes both.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-20 10:23:24 +01:00
Asim Aslam cdc6ee9aa1 examples: support desk agent + blog walkthrough (#2983)
A real-world, runnable example (examples/support): customers/tickets/notify
services become the agent's tools, a flow turns a ticket.created event into
the agent's work, and an approval gate guards the one action that touches a
customer. Runs with no API key (mock model) or against a live provider.

Adds blog/28 'Building a Support Agent in Go' and indexes both.


Claude-Session: https://claude.ai/code/session_01CmdEY7pYmV5zzwCjNJ4ykL

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-19 21:55:50 +01:00
Asim Aslam e5bf72abd8 docs: consolidate to a single agentic/DX roadmap (#2982)s
Replace the drifted, contradictory roadmap set (two public roadmaps, the
AI-native-era business-model doc, stale status snapshots) with one
canonical roadmap focused on agentic development and developer experience.

- internal/website/docs/roadmap.md — the single source of truth: where we
  are (v6), the principles (build into what people run; CLI-first; the
  0->1 and 0->hero getting-started contract; interaction; battle-tested),
  and prioritized work (cross-provider conformance + resilience now;
  durable agent loop, streaming, observability next).
- ROADMAP.md — concise, points to the canonical.
- roadmap-2026 + the internal ROADMAP_2026/STATUS docs — collapsed to
  pointers (keeps blog/CLAUDE links alive, removes drift).
- CLAUDE.md — references the single roadmap + CHANGELOG for status.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-19 20:11:02 +01:00
Asim Aslam 232126476a Revise acknowledgment for sponsorship and Discord invite
Updated the acknowledgment section to reflect sponsorship and invite discussion.
2026-06-19 19:27:13 +01:00
Asim Aslam 358b2ffd27 Update blog post to refine 'Flows' definition
Clarified the definition of 'Flows' to include agents and corrected minor wording issues.
2026-06-19 17:53:44 +01:00
Asim Aslam 45346337e2 Update V3 description for clarity and accuracy
Clarified the description of V3 and its market reception.
2026-06-19 17:50:21 +01:00
Asim Aslam 4b8b4d7bab Fix typo in blog post about Go Micro development 2026-06-19 17:35:57 +01:00
Asim Aslam 97f932a2e7 Revise blog post on Go Micro's revival and evolution
Updated the blog post to reflect the journey of Go Micro, including its revival and the integration of agents into the framework. Enhanced clarity and structure throughout the text.
2026-06-19 17:23:15 +01:00
Asim Aslam ca87efef2f feat(agent): expose run metadata + structured guardrail reasons to tool wrappers (#2981)
goreleaser / goreleaser (push) Waiting to run
Closes the remaining ask in #2980 without adding a parallel callback API.
ToolResult.Refused tags a guardrail block with a reason (ai.RefusedLoop /
RefusedMaxSteps / RefusedApproval) so a wrapper can switch on it instead of
parsing the message. ai.RunInfo (RunID, ParentID, Agent) rides on the
context passed to the tool handler, giving wrappers run correlation and
delegation lineage. Before/after/retry/failure were already covered by
AgentWrapTool; this adds the metadata. Docs + tests included.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-19 08:09:22 +01:00
Asim Aslam d54cfab1bd blog: Bringing an Open Source Project Back from the Dead (#27) (#2979)
A first-person journey of Go Micro from January 2015 through the
VC/company era, the platform pivot, the quiet years, and the revival via
the Claude Code grant — into v6 and the services/agents/flows model.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-18 19:41:08 +01:00
Asim Aslam 46c56ef7df test(natsjs): fix flaky TempDir cleanup race + vet-unsafe Fatalf (#2978)
TestSingleEvent intermittently failed on cleanup with 'directory not
empty': the embedded NATS JetStream server was still releasing files when
t.TempDir's RemoveAll ran at test end. Own the store dir (os.MkdirTemp)
and remove it only after server.Shutdown()+WaitForShutdown(). Also report
setup errors with Errorf instead of Fatalf/require, which are unsafe from
the non-test goroutine (go vet).

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-18 12:06:19 +01:00
Asim Aslam c7657f73f4 Refactor agent plan storage, update docs, and release v6 (#2977)
goreleaser / goreleaser (push) Waiting to run
* test(harness): read agent plan from the scoped store

The store-scoping change moved an agent's plan from the default table
key agent/{name}/plan to its own table (database "agent", table {name},
key "plan"). The plan-delegate harness tests still read the old key and
failed with 'not found'; read through store.Scope(mem, "agent", name)
like the agent does.

* docs: orient agents-first across README, landing, and docs overview

Lead with agents (then services and flows), surface MCP + A2A as the
interop story, and frame agents as services. Landing hero and feature
grid reordered agents-first with an A2A gateway card.

* v6: module path go-micro.dev/v6, TLS secure by default, NewService

Cut v6. Three breaking changes, bundled so the major bump is paid once:

- Module path go-micro.dev/v5 -> go-micro.dev/v6 across all imports + go.mod.
- TLS verification on by default (was off). MICRO_TLS_SECURE removed;
  MICRO_TLS_INSECURE=true opts out for self-signed/dev.
- micro.NewService(name, opts...) is the canonical service constructor,
  symmetric with NewAgent/NewFlow; micro.New kept as a deprecated alias;
  the old name-less NewService(opts...) removed. Generators emit NewService.

Also ports the JWT auth token provider in-module (go-micro.dev/v6/auth/jwt/token
on golang-jwt/jwt/v5), dropping the v5-pinned github.com/micro/plugins/v5/auth/jwt
and the deprecated dgrijalva/jwt-go.

Docs/README/landing updated to v6 and @latest; v5->v6 migration guide added;
CHANGELOG cut as [6.0.0]. Blog posts left at their historical versions.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-18 11:55:35 +01:00
Asim Aslam b9586f920b test(harness): read agent plan from the scoped store (#2976)
The store-scoping change moved an agent's plan from the default table
key agent/{name}/plan to its own table (database "agent", table {name},
key "plan"). The plan-delegate harness tests still read the old key and
failed with 'not found'; read through store.Scope(mem, "agent", name)
like the agent does.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-18 11:04:14 +01:00
Asim Aslam f42c9d1d69 feat(a2a): agents can serve A2A directly, no gateway required (#2975)
Refactor the A2A handler into a reusable dispatcher + Invoke seam and
expose NewAgentHandler(card, invoke) + Card(). An agent now serves its
own A2A endpoint with AgentA2A(addr) / WithA2A — handling tasks
in-process (no RPC hop, no separate gateway). The gateway and embedded
agent share the same handler; the only difference is RPC vs in-process
invocation. Docs, README, and changelog cover both deployment modes.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-18 10:57:38 +01:00
Asim Aslam 307b94aab7 Implement A2A protocol gateway and update documentation (#2974)
goreleaser / goreleaser (push) Waiting to run
* feat(a2a): Agent2Agent protocol gateway

Add gateway/a2a — exposes registered agents over the open A2A protocol so
agents on other frameworks can discover and call them. Agent Cards are
generated from registry metadata (the same way the MCP gateway derives
tools from service endpoints); incoming A2A tasks translate to the
agent's existing Agent.Chat RPC, so there's no per-agent code.

v1 is the synchronous JSON-RPC binding: message/send returns a completed
Task, tasks/get retrieves it, and Agent Cards are served for discovery;
streaming and push notifications are advertised as unsupported. Run with
'micro a2a serve' (cmd/micro/a2a). Tests cover card generation,
message/send, tasks/get, listing, and unknown-method errors.

* docs: A2A guide, README contents + A2A section, universe A2A check

- Add a Contents table of contents at the top of the README and an A2A
  subsection under Building Agents.
- Add the Agent2Agent (A2A) guide and register it in the docs nav.
- Exercise the A2A gateway in the universe harness: the concierge agent
  is reached over A2A (message/send -> Agent.Chat -> completed task).

* feat(a2a): outbound client — call external A2A agents

Add a2a.Client (Send/Card) so a Go Micro agent or flow can call an agent
on any framework by URL — the outbound counterpart to the gateway. Wired
in two places: flow.A2A(url) as a workflow step (the cross-framework
Dispatch), and agent delegate to an http(s) URL routes over A2A. The
universe harness now drives the gateway through the client, exercising
both directions. Tests cover client send/card and the round trip.

* docs: A2A both-directions — guide, README, changelog, blog #26

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-17 20:33:20 +01:00
Asim Aslam 7ee32e8721 Update changelog and enhance retrospective blog on agentic features (#2973)
* docs: changelog catch-up + retrospective blog (agentic development)

Add the headline agentic features that shipped this quarter but were
never logged (agents, plan/delegate, guardrails, workflows, x402) to the
changelog, and add blog #25 — a three-month progress reflection on Go
Micro becoming a framework for agentic development.

* docs: tighten retrospective post — cut slogans, triads, and filler

* docs: tighten retrospective intro, bridge, and conclusion for a single through-line

* docs: frame Go Micro as how you build a distributed system, not run one

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-17 12:29:25 +01:00
Asim Aslam 9fdcc24cce Implement durable execution and scoped state management for flows (#2972)
* docs: design note for flow steps + Checkpoint durable execution

* docs: fold in durable-execution decisions (State struct, single Step, run retention, retry)

* docs: rename State.Payload to State.Data

* feat(flow): ordered steps + Checkpoint durable execution

A flow can now be an ordered list of steps (a task with stages) instead
of a single LLM turn. State carries typed Data plus a Stage marker; each
step is checkpointed before and after via a pluggable Checkpoint
(store-backed by default), so a run survives a crash and resumes where it
stopped without re-running completed steps. Flow-level Retry with a
per-step override; runs retained for audit unless DeleteOnSuccess.

Step actions: Call (RPC), LLM (augmented turn), Dispatch (to an agent),
or any StepFunc. Single-step and agent-dispatch flows are unchanged.

* feat(flow): top-level re-exports + durable flow example

Expose the step/checkpoint API from the micro package (FlowSteps,
FlowStep, FlowState, FlowRetry, FlowWithCheckpoint, FlowCall/LLM/Dispatch,
Checkpoint, StoreCheckpoint) and add a runnable, key-free example
demonstrating crash + resume.

* docs: document durable flow steps (guide, README, CLI help)

* docs: blog post + changelog for durable workflows

* fix(flow): scope checkpoint keys by flow name (flow/{name}/runs/{id})

Run keys were flow/runs/{id} — a single global keyspace shared by every
flow on the default store. Namespace them by flow name so each flow's
state is kept apart. StoreCheckpoint now takes a scope argument (the flow
passes its name by default).

* feat(store): Scope handle; scope agent and flow state by name

Add store.Scope(s, database, table) — a store handle that confines every
operation to a database/table without mutating the shared store, so
co-located components don't clobber each other's table (the failure mode
of the global Init(Table(...)) approach).

Use it to keep each agent's memory and plan in its own table
(agent/{name}) and each flow's runs in its own (flow/{name}), instead of
one global table partitioned only by key prefix. Services already scope
by service name.

* feat: consistent state model — service store scoping, flow registry, list/history CLI

- service: scope store via store.Scope (database service / table name),
  retiring the Init(store.Table(name)) global-mutation hack; bridge the
  default store so handlers using store.DefaultStore stay isolated.
- flow: register in the registry as type=flow while running (with trigger
  and step count), deregister on Stop. Live discovery, like agents.
- cli: micro flow list (registry), micro flow runs <name> (durable store),
  micro agent history <name> (durable store). list = running, runs/history
  = durable, mirroring the service model.

* test: mini-universe end-to-end harness + scheduled GitHub Action

internal/harness/universe boots a small but real go-micro world — four
services, a durable checkout flow that crashes at payment and resumes,
and a guardrailed agent with a tool wrapper reached over RPC — drives the
scenario, asserts the end state (10 checks), and shuts down. Everything
is real except the LLM (mocked), so it's deterministic and needs no key;
-provider anthropic runs it live. Exits non-zero on failure, so it's an
end-to-end test, not just a demo.

Adds .github/workflows/universe.yml (push/PR/daily/dispatch) running the
universe + existing harnesses on the mock provider, plus an opt-in job
that runs live when ANTHROPIC_API_KEY is set. 'make harness' runs them
locally.

* ci: run the live universe job against AtlasCloud (ATLASCLOUD_API_KEY)

* ci: run the live universe job only on schedule or manual dispatch

The deterministic mock job still runs on push/PR/daily; the live
(AtlasCloud) job runs daily and on manual workflow_dispatch only, so
changes don't burn API credits on every PR but can still be checked
against a real model on demand.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-17 12:02:47 +01:00
Asim Aslam 6b4ce55a7c Implement tool-execution wrappers and update documentation (#2971)
* feat(agent): tool-execution wrappers via WrapTool

Restructure ai.ToolHandler to the structured, ctx-carrying shape that
mirrors a go-micro RPC handler:

    func(ctx context.Context, call ai.ToolCall) ai.ToolResult

This reuses the existing ToolCall (with its correlation ID) and
ToolResult types instead of the flat (name, input)->(any, string)
signature, and adds ToolCall.Scan for typed argument access.

Add ai.ToolWrapper and the agent option WrapTool / micro.AgentWrapTool —
the tool-side analogue of client.CallWrapper and server.HandlerWrapper.
Reframe the built-in guardrails (MaxSteps, LoopLimit, ApproveTool) as
composed wrappers around a base handler; developer wrappers compose
outermost, so they observe every call and result, including refusals.

Update all provider call sites, the MCP server and chat handlers, the
integration harnesses, and docs to the new signature.

* examples: add agent-wrap-tool showing AgentWrapTool

A runnable example of tool-execution middleware: an observe wrapper that
times calls and records per-tool metrics (correlated by call ID), and a
retry wrapper that recovers a flaky service call before the model sees
it. Demonstrates outermost-first composition and the wrapper/guardrail
interaction (retries are seen by loop detection).

* docs: note AgentWrapTool in README capabilities and CHANGELOG

* fix(generate): pin scaffolded go.mod to one version constant

The two generators pinned different, stale go-micro versions (v5.24.0
for services, v5.25.0 for agents). Centralize on a single
goMicroVersion constant (v5.29.0) so generated services and agents stay
in sync with the framework and there's one place to bump on release.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-17 09:52:27 +01:00
Asim Aslam ce0741a80c Implement tool-execution wrappers and restructure ToolHandler (#2970)
* feat(agent): tool-execution wrappers via WrapTool

Restructure ai.ToolHandler to the structured, ctx-carrying shape that
mirrors a go-micro RPC handler:

    func(ctx context.Context, call ai.ToolCall) ai.ToolResult

This reuses the existing ToolCall (with its correlation ID) and
ToolResult types instead of the flat (name, input)->(any, string)
signature, and adds ToolCall.Scan for typed argument access.

Add ai.ToolWrapper and the agent option WrapTool / micro.AgentWrapTool —
the tool-side analogue of client.CallWrapper and server.HandlerWrapper.
Reframe the built-in guardrails (MaxSteps, LoopLimit, ApproveTool) as
composed wrappers around a base handler; developer wrappers compose
outermost, so they observe every call and result, including refusals.

Update all provider call sites, the MCP server and chat handlers, the
integration harnesses, and docs to the new signature.

* examples: add agent-wrap-tool showing AgentWrapTool

A runnable example of tool-execution middleware: an observe wrapper that
times calls and records per-tool metrics (correlated by call ID), and a
retry wrapper that recovers a flaky service call before the model sees
it. Demonstrates outermost-first composition and the wrapper/guardrail
interaction (retries are seen by loop detection).

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-16 17:26:30 +01:00
Asim Aslam 5e5d253abd feat(agent): tool-execution wrappers via WrapTool (#2969)
Restructure ai.ToolHandler to the structured, ctx-carrying shape that
mirrors a go-micro RPC handler:

    func(ctx context.Context, call ai.ToolCall) ai.ToolResult

This reuses the existing ToolCall (with its correlation ID) and
ToolResult types instead of the flat (name, input)->(any, string)
signature, and adds ToolCall.Scan for typed argument access.

Add ai.ToolWrapper and the agent option WrapTool / micro.AgentWrapTool —
the tool-side analogue of client.CallWrapper and server.HandlerWrapper.
Reframe the built-in guardrails (MaxSteps, LoopLimit, ApproveTool) as
composed wrappers around a base handler; developer wrappers compose
outermost, so they observe every call and result, including refusals.

Update all provider call sites, the MCP server and chat handlers, the
integration harnesses, and docs to the new signature.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-16 16:26:56 +01:00
Asim Aslam e079e083da feat(agent): loop detection guardrail + document/blog agent guardrails (#2968)
Add LoopLimit: refuse a tool call repeated with identical arguments in
one Ask, with a self-heal message so the model changes approach. Catches
the no-progress loop that MaxSteps (count) and the gateway circuit
breaker (failures) miss. Enforced at the same tool-handler choke point as
MaxSteps/ApproveTool; on by default (lenient 3); AgentLoopLimit(0) to
disable. Tests cover repeats, distinct calls, disabled, and default-on.

Docs: new Agent Guardrails guide (MaxSteps/LoopLimit/ApproveTool, the
ApproveTool integration seam for external policy engines, and the
gateway's RateLimit/CircuitBreaker), nav + README + AGENT_DESIGN updates,
and blog/23 'Agent Guardrails'.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-16 14:40:05 +01:00
Asim Aslam a1a57799c3 Add payment requirements to tool catalog and implement x402 client (#2966)
* feat(mcp): advertise x402 payment requirements in the tool catalog

/mcp/tools now includes each priced tool's payment requirements (amount,
network, asset, payTo) when payments are enabled, so an agent can see the
cost before calling and choose by price — a shoppable catalog, the
foundation for a tool marketplace. Free tools carry no payment block; the
shared Tool struct is copied when pricing so it isn't mutated. Tests cover
priced/free tools and payments-disabled. Documented in the payments guide.

* feat(x402): consumer client with a spend budget (pay-and-retry)

Add x402.Client, the consumer counterpart to Middleware: it settles 402
challenges automatically via a pluggable Payer, up to a spend Budget. A
call that would exceed the budget is refused before any payment is made,
and spend accumulates across calls — the spend cap that keeps an
autonomous, paying caller in bounds. Tests cover pay-within-budget,
refuse-over-budget, budget accumulation, and free endpoints, end to end
against the server Middleware with a mock facilitator and payer. Guide
documents the consumer side; agent-level AgentMaxSpend is the next step.

* chore: gofmt gateway/mcp/benchmark_test.go (trailing newline)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-15 21:12:29 +01:00
Asim Aslam e4d2a41c32 refactor(x402): Amount/Amounts naming + per-tool amounts + docs (#2965)
goreleaser / goreleaser (push) Waiting to run
Follow-up to the merged x402 integration (#2964). Drop the commerce-y
'price' vocabulary for the protocol's own 'amount', and add per-tool
pricing as an operator concern (the way scopes/rate-limits are set at the
gateway).

- x402.Config: Price -> Amount (default), plus Amounts map for per-tool
  overrides; AmountFor(tool) resolves per-tool -> default. Add a Require
  primitive (per-request enforcement) and LoadConfig for an operator
  config file.
- MCP gateway: enforce payment per-tool inside /mcp/call (where scopes
  are enforced) using AmountFor, instead of a flat path-based middleware.
- CLI: --x402-price -> --x402-amount; add --x402-config (per-tool file)
  to micro mcp serve and micro-mcp-gateway.
- docs: new Payments (x402) guide + nav + README section; blog/22
  updated to Amount/Amounts and the config-file model.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-15 17:04:34 +01:00
Asim Aslam 9deac487cb feat(x402): opt-in agent-native payments for tools (#2964)
Integrate the x402 payment protocol (HTTP 402) so a tool can require a
stablecoin payment and an agent can settle it — the next step after
autonomous agents (blog 21): agents that act, and pay.

- wrapper/x402: HTTP middleware enforcing the 402 challenge/verify flow,
  with a pluggable Facilitator interface. Go Micro carries no chain or
  crypto code — verification/settlement is delegated to a facilitator
  (Coinbase CDP, Alchemy, self-hosted), so Base and Solana are just
  different facilitators behind one interface. HTTPFacilitator default;
  tests cover challenge / accept / reject via a mock facilitator.
- MCP gateway: optional Options.Payment gates /mcp/call (listing tools
  and health stay free); off unless configured.
- micro mcp serve and micro-mcp-gateway: opt-in --x402-pay-to/-price/
  -network/-facilitator flags (env vars on the standalone binary).
- blog/22 'Integrating x402: Payments for Agents'; README feature row.

Pricing is flat per call for now; richer models and an agent-side spend
cap (next to MaxSteps/ApproveTool) are follow-ups.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-15 16:41:25 +01:00
Asim Aslam 6eec83a045 blog: 'When the Event Is the Prompt' (#21) + autonomous agent-flow harness (#2962)
The autonomy direction: agents that run on events, not human prompts.

- internal/harness/agent-flow: a runnable, deterministic demo — a
  user.created broker event drives a Flow that hands off to a registered
  agent (FlowAgent), which creates a workspace and sends a welcome over
  real RPC. Only the LLM is mocked; passes under -race.
- blog/21: 'When the Event Is the Prompt' — the shift from agents you
  talk to, to agents that act on their own; where microagents become
  real; and the honest bar autonomy raises (guardrails, observability,
  durable/resumable execution — the next things to build).

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-15 12:16:08 +01:00
Asim Aslam 9dae4e34b7 Enhance README with sponsorship CTA and improve agent architecture (#2961)
* docs: add 'become a sponsor' call-to-action linking to Discord

Now that there are a couple of sponsors, invite more: a short CTA under
the Sponsors section in the README and on the landing page, pointing to
the Discord to get in touch.

* fix(health): remove duplicate RegistryCheck declaration

Two PRs (#2957 and #2958) each added a RegistryCheck to the health
package, leaving the package uncompilable on master (RegistryCheck
redeclared: health/registry.go vs health/health.go). Keep the
health.go implementation — it honors the check's context timeout so a
hung registry (e.g. an unreachable etcd) reports down instead of
blocking the probe — and remove the duplicate registry.go and its test.
registry_check_test.go already covers healthy/down/nil/timeout/not-ready.

* feat(agent): pluggable memory and custom tools

Make agents compose the way services do — pluggable pieces with working
defaults — by adding the two abstractions an agent needs beyond the model:

- Memory: a pluggable interface for conversation memory. The default is
  store-backed and durable across restarts (the previous hardcoded
  behavior, now behind an interface); supply your own with WithMemory
  (in-memory, database, semantic store). NewMemory / NewInMemory provided.
- Custom tools: WithTool registers any function as a tool the agent can
  call, so agents are no longer limited to orchestrating RPC services.

Both exposed at the micro package (AgentMemory, AgentTool, NewMemory,
NewInMemory). Behavior-preserving refactor of the agent's history into
the default Memory; tests cover persistence, in-memory, clear, custom
tool dispatch and errors. README + AGENT_DESIGN document the pluggable
composition (model / memory / tools / guardrails).

* blog: 'Doubling Down on Agents' (#20)

The vision post for making agents a first-class framework the way
services were: opinionated, batteries-included, pluggable. Frames an
agent as a composition of model + memory + tools + guardrails with
working defaults; introduces the new pluggable memory and custom tools;
makes the microagents argument (an agent for everything, distributed
like microservices); and lays out the three primitives — services,
agents, workflows — as one substrate, with an honest list of the gaps
still to fill (knowledge/retrieval, streaming, explicit loop).

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-10 11:04:23 +01:00
Asim Aslam b41dfa02f2 docs: add 'become a sponsor' call-to-action linking to Discord (#2960)
Now that there are a couple of sponsors, invite more: a short CTA under
the Sponsors section in the README and on the landing page, pointing to
the Discord to get in touch.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-10 10:30:10 +01:00
Copilot 0b41c71681 feat(health): add RegistryCheck for registry connectivity health checks (#2957)
goreleaser / goreleaser (push) Waiting to run
* Initial plan

* feat(health): add RegistryCheck for registry connectivity health checks

Add a RegistryCheck function to the health package that creates a health
check verifying connectivity to the service registry. This enables
Kubernetes readiness probes to detect when a service loses its connection
to the registry (e.g. etcd).

Usage:
  health.Register("registry", health.RegistryCheck(reg))

* fix(health): simplify error assertion in registry check test

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-06-10 08:25:23 +01:00
Asim Aslam 550033dcce Optimize image formats and fix lease re-registration issue (#2959)
* perf: convert generated PNGs to optimized JPEGs (12MB -> 1.5MB)

The landing and docs loaded 18 AI-generated PNGs at 0.5-1MB each. They're
1200x800 RGB illustrations with no transparency, so they recompress ~8x
as progressive JPEG (quality 82) with no visible loss. Convert all,
update every reference (.png -> .jpg), and drop the originals (including
the unused hero.png). Generated images: 12.3MB -> 1.5MB.

* fix(registry/etcd): re-register when a lease silently expires (#2956)

The keepalive rework (long-lived KeepAlive instead of KeepAliveOnce)
moved lease renewal entirely onto the keepalive goroutine; the 30s
periodic Register now skips on the 'unchanged' check. The goroutine only
reacted to the keepalive channel closing, so a lease that expired
server-side without a prompt channel close (e.g. a partition that
outlasted the 90s TTL) left the node de-registered from etcd while the
cache still believed it was registered — and nothing re-registered it.
That is the hidden-failure mode reported in #2956.

React to a non-positive TTL keepalive response the same as a channel
close: drop the cached lease/hash so the next Register performs a full
re-registration. Extract the loop into keepAliveLoop and unit-test the
TTL-expired, channel-closed, and healthy paths (no etcd required).

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-10 08:24:49 +01:00
Asim Aslam 584a9f2132 feat(health): add RegistryCheck for registry connectivity (#2956) (#2958)
A go-micro service can keep running while it has silently lost its
connection to the registry (etcd, Consul, …) — the process looks healthy
but other services can no longer discover it, and Kubernetes sees the
pod as fine. health.RegistryCheck(reg) probes connectivity via
ListServices and, registered as a critical check, makes /health/ready
report not-ready so a readiness probe can pull the pod from rotation.

- Works with any registry implementation (no interface change).
- Honors the check timeout: an unreachable/hung registry is reported
  down rather than blocking the probe.
- Tests cover healthy, down, timeout, nil, and the not-ready integration.
- Documented in the health guide with the Kubernetes readiness example.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-10 08:18:00 +01:00
Asim Aslam 6488d8402d Organize README features, enhance testing, and update docs (#2955)
* docs: group README features by section (AI / Framework / DX)

The features table repeated 'AI' down the Category column. Split into
three grouped tables — AI, Framework, Developer experience & deployment —
dropping the repetitive column. Adds a Guardrails row (MaxSteps,
ApproveTool).

* test: flow-to-agent end-to-end in the harness

Proves 'Flow triggers, Agent reasons': a workflow with FlowAgent hands an
event to the registered conductor agent over RPC, which plans, creates
tasks, and delegates to comms — the whole chain over real RPC with only
the LLM mocked. Deterministic (shared in-memory registry, no sleeps),
passes under -race.

* blog: 'The Evolution of Microservices' (#19)

A technical history of distributed-systems eras — the monolith's
coordination cost, the distributed-systems tax, containers and
declarative orchestration, the service mesh, and the modular-monolith
correction — establishing the durable unit (named, typed, discoverable,
independently deployable) that every runtime wave required. Then the
technical argument for agents: an LLM tool call needs exactly a service
interface, so the caller shifts from deterministic code to a reasoner
that composes typed capabilities from intent, with the honest caveats
(non-determinism, cost, guardrails). Not a product pitch.

* docs: bump install version to v5.27.0

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-08 10:16:05 +01:00
Asim Aslam d3be610367 Refactor README features and add end-to-end flow testing (#2954)
goreleaser / goreleaser (push) Waiting to run
* docs: group README features by section (AI / Framework / DX)

The features table repeated 'AI' down the Category column. Split into
three grouped tables — AI, Framework, Developer experience & deployment —
dropping the repetitive column. Adds a Guardrails row (MaxSteps,
ApproveTool).

* test: flow-to-agent end-to-end in the harness

Proves 'Flow triggers, Agent reasons': a workflow with FlowAgent hands an
event to the registered conductor agent over RPC, which plans, creates
tasks, and delegates to comms — the whole chain over real RPC with only
the LLM mocked. Deterministic (shared in-memory registry, no sleeps),
passes under -race.

* blog: 'The Evolution of Microservices' (#19)

A technical history of distributed-systems eras — the monolith's
coordination cost, the distributed-systems tax, containers and
declarative orchestration, the service mesh, and the modular-monolith
correction — establishing the durable unit (named, typed, discoverable,
independently deployable) that every runtime wave required. Then the
technical argument for agents: an LLM tool call needs exactly a service
interface, so the caller shifts from deterministic code to a reasoner
that composes typed capabilities from intent, with the honest caveats
(non-determinism, cost, guardrails). Not a product pitch.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-08 09:09:48 +01:00
Asim Aslam 35bc58e5d2 Enhance onboarding experience and clarify workflows vs agents (#2953)
* blog: 'Not Everything Should Be an Agent' (#18) on workflows

The workflow counterpart to the plan/delegate post: when the path is
known, use a deterministic Flow, not an autonomous agent. Frames flow vs
agent as two modes of the same building blocks, covers flow-triggers-
agent dispatch and the agent guardrails, and gives the simplest-first
guidance (single call -> workflow -> agent). Continues the arc from
blog 14/16/17; references Building Effective Agents in passing.

* docs: fix new-user onboarding friction

- README: lead Quick Start with a no-key 30-second path (micro new ->
  micro run -> curl), then the AI --prompt path with an explicit
  'export ANTHROPIC_API_KEY' so the headline command no longer fails
  silently for users without a key.
- Unify all install versions to v5.26.0 (README + docs were split across
  v5.16.0 / v5.25.0).
- Refresh the docs landing overview from the old 'microservices
  framework' framing to 'services and agents', matching the README.
- getting-started: add Prerequisites (Go 1.21+, and that a provider key
  is only needed for AI features).
- README features: Flows -> Workflows wording.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-08 08:52:11 +01:00
Asim Aslam e416ea4a75 Enhance agent workflows with guardrails and documentation updates (#2952)
* docs: map go-micro onto Anthropic's workflows-vs-agents taxonomy

- new guide 'Agents and Workflows': adopts Anthropic's Building Effective
  Agents vocabulary — workflow (predefined path) = flow, agent (dynamic
  self-direction) = agent — maps the augmented-LLM building block and the
  five workflow patterns onto go-micro, and shows routing (chat router)
  and orchestrator-workers (conductor + plan/delegate) are already native.
- flow package doc reframed as a workflow (predefined path) per the same
  taxonomy, with guidance on flow vs agent.
- nav + README link the new guide.

* feat: agent guardrails — step limit and tool approval hook

Anthropic's Building Effective Agents stresses stopping conditions and
human-in-the-loop checkpoints for autonomous agents. Add both as plain
options enforced at the tool-handler choke point — no provider changes,
no new abstraction:

- MaxSteps(n): bound tool executions per Ask; beyond the limit, actions
  are refused and the model is told to stop and summarize.
- ApproveTool(fn): gate each action before it runs; returning false
  blocks it and surfaces the reason to the model. The internal plan tool
  is never gated.

Exposed at the micro package (AgentMaxSteps, AgentApproveTool, ApproveFunc).
Tests cover the limit, blocking, and that plan is not gated. Guardrails
section of the agents-and-workflows guide updated from 'active work' to
documented options.

* feat: flow can dispatch to an agent (flow triggers, agent reasons)

Unify the engine without collapsing the workflow/agent distinction. A
Flow with Agent set hands each event's rendered prompt to a named
registered agent over RPC (Agent.Chat) instead of running its own LLM
step — so the workflow stays the deterministic trigger and the agent is
the reasoning engine, with its plan, delegate, memory, and guardrails.
A plain flow is unchanged (single augmented-LLM step).

- flow.Agent(name) / micro.FlowAgent(name); flow stores the client and
  skips model setup when dispatching.
- test: dispatch routes to comms.Agent.Chat with the rendered prompt and
  records the reply.
- guide: 'Flow triggers, Agent reasons' section.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-08 08:32:32 +01:00
Asim Aslam 830c8d84c2 Claude/loving meitner 3 etoi (#2951)
* rename coordinator agent to conductor in example and docs

* add plan & delegate integration harness

Runs the real go-micro stack end to end — services, registry, RPC, the
agent loop, store, and delegate-first routing — with only the LLM mocked
by a deterministic provider. Proves discovery, tool execution, plan
persistence, and agent-to-agent delegation over RPC work without an API
key; swap the provider to run the same flow against a live model.

* test: deterministic CI integration test + provider flag for harness

- main_test.go: TestPlanDelegateEndToEnd drives the full real stack
  (services, RPC, agent loop, store, delegate-first routing) over a
  shared in-memory registry — no mDNS, no sleeps. Asserts 3 tasks
  created via RPC, plan persisted to the store, and delegation reaching
  the comms agent (notify called once). Passes under -race, ~0.03s.
- main.go: add -provider flag (defaults to mock) and key detection so the
  same harness runs against a live model with no code change.

* chore: gitignore built harness/example binaries

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-07 19:28:24 +01:00
Asim Aslam 6a73608e9c rename coordinator agent to conductor in example and docs (#2950)
Co-authored-by: Claude <noreply@anthropic.com>
2026-06-07 18:33:04 +01:00
Asim Aslam cb33decd97 Add built-in plan and delegate tools for agents with examples (#2949)
* feat: add plan and delegate as built-in agent tools

Give agents two self-capabilities, expressed as plain tools wired into
the existing tool handler — no harness or graph, consistent with
"services are the only abstraction":

- plan: record/update an ordered plan, persisted to store-backed memory
  and surfaced in the system prompt on later turns (externalized
  planning).
- delegate: hand a self-contained subtask to another agent.
  Delegate-first — if the target names a registered agent it is called
  via RPC; otherwise a focused ephemeral sub-agent is created with
  agent.New + Ask in a fresh, isolated context (loads/persists no
  history, no built-in tools, so it cannot re-delegate).

Both are added automatically to any non-ephemeral agent, so existing
micro.NewAgent services and micro chat routing get them for free.
Tests are hermetic (memory store + memory registry).

* feat: add agent-plan-delegate example and document plan/delegate

- examples/agent-plan-delegate: coordinator that plans multi-step work,
  creates tasks with its own tools, and delegates notification to a
  separate registered comms agent over RPC.
- integration tests driving the full Ask loop through a fake provider:
  plan tool exposure + persistence, ephemeral delegation with isolated
  context, delegate-first RPC routing to a registered agent.
- docs: README (Building Agents + features + examples), AGENT_DESIGN
  (Built-in Capabilities), agent-patterns guide (Pattern 9), CLAUDE.md.

* docs: blog post and guide for plan & delegate

- blog/17: "Plan & Delegate: Deep Agents in Go" — what the feature is,
  how plan and delegate work, and a runnable getting-started path.
- guides/plan-delegate: reference guide with the smallest-agent snippet,
  plan/delegate semantics, and the multi-agent example; linked in nav.
- example: auto-detect provider/key from common env vars (ANTHROPIC_API_KEY,
  OPENAI_API_KEY, ...) so 'export KEY && go run main.go' just works.
- onboarding: getting-started paths now include go mod init / go get and a
  clone-and-run path, so a reader can actually run it from a cold start.

* refactor: reframe plan/delegate blog and clean up sub-agent construction

- blog/17 retitled "Agents That Plan and Delegate" and reframed around
  intent (plan = state intent, delegate = direct it), positioned as the
  next beat after blog 15/16 and tied to the existing store + agent RPC
  rather than re-announcing them. "Deep agents" now a single in-passing
  nod, matching how blog 14 references LangChain.
- agent: add unexported newEphemeral constructor for sub-agents instead
  of type-asserting the public Agent interface to set an internal field;
  matches the options-only construction idiom used elsewhere.

* feat: expose plan & delegate in the micro chat fallback

Add agent.Builtins(opts...) — returns the built-in tools plus a handler,
so the plan/delegate capabilities can be wired into a tool loop that
isn't a running Agent. micro chat's direct-service fallback now reuses
it (single source of truth, no duplicated handler logic), so planning
and delegation are available there too, not just for registered agents.
Adds a test for the accessor; notes CLI availability in the guide.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-07 10:55:34 +01:00
Asim Aslam 9bed04ced0 Enhance micro run with interactive console and image compression (#2948)
Run Tests / Unit Tests (push) Waiting to run
Run Tests / Etcd Integration Tests (push) Waiting to run
goreleaser / goreleaser (push) Waiting to run
* perf: compress hero image — 1.4MB to 80KB

Resized from 1536px to 1200px, converted to JPEG at quality 80.
80KB loads instantly vs 1.4MB stalling on slower connections.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: micro run drops into interactive console

One command does everything — generate, start, and chat. No
separate micro chat step. The landing page shows micro run
dropping straight into the > prompt.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: interactive console in micro run, -d for detached mode

micro run now drops into an interactive chat console after services
start. The console discovers services, exposes them as tools, and
lets you talk to them through an LLM — same as micro chat but
built into the run experience.

- Detects MICRO_AI_PROVIDER and MICRO_AI_API_KEY from environment
- Falls back to provider-specific env vars (ANTHROPIC_API_KEY, etc.)
- If no API key, prints hint and blocks on Ctrl-C (no console)
- -d / --detach flag skips the console (background mode)
- Ctrl-C always shuts everything down

Removed adopters section from README.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 20:49:25 +01:00
Asim Aslam 2e89961386 perf: compress hero image — 1.4MB to 80KB (#2947)
Resized from 1536px to 1200px, converted to JPEG at quality 80.
80KB loads instantly vs 1.4MB stalling on slower connections.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 14:38:02 +01:00
Asim Aslam 39e8dc7311 Reposition hero section and optimize hero image for landing page (#2946)
* docs: reposition hero — framework for services and agents

Landing page: "Build Services and Agents in Go" — positions as a
framework, not a code generator. Tagline: "A framework for
microservices that AI agents can discover, use, and manage."

Hero command reverts to go get (the framework) instead of
micro run --prompt (a feature).

README matches: "framework for building services and agents in Go."

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* perf: compress hero image — 1.4MB to 80KB

Resized from 1536px to 1200px, converted to JPEG at quality 80.
80KB loads instantly vs 1.4MB stalling on slower connections.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 14:32:35 +01:00
Asim Aslam c93bcdf4d3 Update landing page documentation and fix flow CLI import (#2945)
* docs: remove code references from landing page feature grid

Landing page describes concepts, not APIs. Removed micro.NewAgent()
and micro.NewFlow() code references. Features described in plain
language — what they do, not how to code them.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: update micro flow CLI to import from go-micro.dev/v5/flow

The flow package moved to top-level but the CLI still imported
from the old ai/flow path. Fixed to use go-micro.dev/v5/flow.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 11:20:40 +01:00
Asim Aslam cd760a29f1 Update landing page content and fix CLI import path (#2944)
* docs: remove code references from landing page feature grid

Landing page describes concepts, not APIs. Removed micro.NewAgent()
and micro.NewFlow() code references. Features described in plain
language — what they do, not how to code them.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: update micro flow CLI to import from go-micro.dev/v5/flow

The flow package moved to top-level but the CLI still imported
from the old ai/flow path. Fixed to use go-micro.dev/v5/flow.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 11:12:00 +01:00
Asim Aslam e45d3df0ad docs: remove code references from landing page feature grid (#2943)
Landing page describes concepts, not APIs. Removed micro.NewAgent()
and micro.NewFlow() code references. Features described in plain
language — what they do, not how to code them.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 11:08:17 +01:00
Asim Aslam 6731ee2f0c Update documentation and blogs for RPC-based agent architecture (#2942)
* docs: update blog posts 15 and 16 to reflect RPC-based agents

Blog 15: replaced broker-based agent communication with RPC —
agents are services, they communicate via standard RPC, no pub/sub
hacks. Updated the framework mapping section.

Blog 16: added proto definition, micro call example, and explanation
that agents are real services with proto-defined endpoints. Updated
Ask() method name.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: update agent design doc and blog posts for RPC-based agents

Rewrote AGENT_DESIGN.md — agents are services with proto-defined
Agent.Chat endpoints, communicate via RPC, no broker dependency.
Includes proto definition, CLI examples, generation output.

Blog 15: replaced broker references with RPC.
Blog 16: added proto definition and micro call example.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: purge all stale broker-based agent references

Updated across all surfaces:
- README: agents described as services with RPC, Ask() not Chat(),
  micro call example instead of micro agent chat
- Blog 15: replaced broker communication with RPC description
- Blog 16: replaced "coordinate through the broker" with RPC
- Getting started: agent is a service with proto endpoint, Ask()
  not Chat(), added micro flow CLI commands (run/exec), expanded
  CLI workflow table

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 11:02:45 +01:00
Asim Aslam f7c042ef26 docs: update blog posts 15 and 16 to reflect RPC-based agents (#2941)
Blog 15: replaced broker-based agent communication with RPC —
agents are services, they communicate via standard RPC, no pub/sub
hacks. Updated the framework mapping section.

Blog 16: added proto definition, micro call example, and explanation
that agents are real services with proto-defined endpoints. Updated
Ask() method name.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 10:31:02 +01:00
Asim Aslam 1bc886fa82 Introduce Agent abstraction and integrate with chat router (#2939)
* docs: Agent interface design sketch

Proposes Agent as a top-level abstraction alongside Service in the
micro package. Agent manages services — scoped tools, system prompt,
conversation memory, registry-discoverable.

Design only, no implementation.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: Agent as a first-class abstraction

Introduce micro.NewAgent() alongside micro.New() — Agent is to
intelligence what Service is to capability.

Agent interface:
- Chat(ctx, message) (*Response, error) — core interaction method
- Run() — registers in registry, subscribes to broker, blocks
- Stop() — graceful shutdown
- Scoped tools — only sees endpoints of its assigned services
- Persistent memory — conversation history stored in store
- Agent-to-agent — communication via broker topics

Top-level API:
  agent := micro.NewAgent("task-mgr",
      micro.AgentServices("task"),
      micro.AgentPrompt("You manage tasks."),
      micro.AgentProvider("anthropic"),
  )
  agent.Run()

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: wire agents into chat router, add micro agent CLI, expose Flow

Three top-level abstractions:
  micro.New("task")              — Service (capability)
  micro.NewAgent("task-mgr")     — Agent (intelligence)
  micro.NewFlow("onboard-user")  — Flow (event-driven orchestration)

micro chat as router:
- Discovers agents from registry on startup
- Single agent: routes directly
- Multiple agents: LLM classifies intent, dispatches to right agent
  via route_to_agent tool
- No agents: falls back to current direct-service behaviour
- Banner shows discovered agents

micro agent CLI:
- micro agent list — shows registered agents and their services
- micro agent describe <name> — shows agent details from registry

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: move flow to top level, update docs for three abstractions

Package structure now consistent:
  service/   — Service (capability)
  agent/     — Agent (intelligence)
  flow/      — Flow (event-driven orchestration)

ai/flow/ kept as backward-compatible re-export.

Updated across all surfaces:
- CLAUDE.md: added agent/ and flow/ to project structure
- README: added "Building Agents" section with NewAgent() examples,
  updated features table (Agents, Flows, Chat router), CLI table
  (agent list, agent describe), docs links
- Website: features grid shows Services, Agents, Flows as the three
  pillars alongside generation, MCP, and pluggable architecture
- micro.go: Flow imported from top-level flow/ package

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: rewrite getting-started, fix ai-integration import paths

Getting started now covers all three abstractions:
- Service (write handlers, micro run, templates)
- Agent (micro.NewAgent, scoped tools, memory, CLI)
- Flow (event-driven LLM orchestration)
Leads with prompt-based generation, then manual service creation.

ai-integration.md: fixed flow import path from go-micro.dev/v5/ai/flow
to go-micro.dev/v5/flow, updated stack diagram to show agent/flow/chat.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* blog: Introducing micro.NewAgent()

Post 16 — announces Agent as a first-class abstraction. Shows the
API (NewAgent, AgentServices, AgentPrompt, AgentProvider), scoped
tools, persistent memory, multi-service agents, multi-agent systems,
and the three-abstraction comparison table (Service/Agent/Flow).

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: fix agent registration, blog post 16

Agent registration:
- Add node with address so mDNS can discover agents
- Store type and services in node metadata (mDNS requirement)
- Connect broker before subscribing, non-fatal if broker unavailable
- Print registration confirmation on Run()

Agent/chat discovery:
- Check both service-level and node-level metadata for type=agent
  (mDNS stores metadata on nodes, not services)

Blog post 16: "Introducing micro.NewAgent()" — announces the Agent
abstraction with code examples, comparison table, multi-agent patterns.

Tested end-to-end: micro run → micro agent list discovers the agent →
micro chat routes to it → agent calls service endpoints.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: agents are proper services with RPC Chat endpoint

Refactored agent to use server.Server instead of fake registry entries.
An agent now:
- Creates a real RPC server with server.Name(agentName)
- Registers an Agent.Chat handler callable via standard RPC
- Sets server metadata type=agent, services=x,y for discovery
- No more fake addresses or broker hacks

micro chat calls agents via RPC (client.Call) instead of creating
local agent instances. The registry stays clean — agents are real
services with real endpoints.

Removed broker dependency from agent options. Agent-to-agent
communication is just RPC like everything else.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: agent uses proto-defined RPC interface

Added agent/proto/agent.proto with Agent service definition:
  rpc Chat(ChatRequest) returns (ChatResponse)

Agent now implements the generated AgentHandler interface and
registers via pb.RegisterAgentHandler. The Chat endpoint is a
standard proto-based RPC callable by any go-micro client.

Renamed the programmatic API from Chat() to Ask() to avoid
collision with the proto handler method name.

micro chat calls agents via standard RPC with JSON-encoded
request/response — no special types needed on the caller side.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: generate agent alongside services, update all docs

micro run --prompt now generates an agent binary that manages all
the generated services. The agent reads MICRO_AI_PROVIDER and
MICRO_AI_API_KEY from the environment. micro run propagates these
when started with --prompt.

Run banner shows services and agents separately.

Updated README, getting-started guide, and landing page to show
the complete flow: generate → services + agent start → micro chat
routes to agent → agent orchestrates services.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-05 10:25:14 +01:00
Asim Aslam 844ac5bc52 Revamp landing hero and introduce agent-based microservices model (#2938)
* docs: update landing hero — describe it, run it, talk to it

Lead with the AI-first experience instead of "write services in Go."
The entry point is now describing what you need, not writing code.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* blog: Agents for Services — a new model for microservices

Post 15 — explores the concept of distributed agents managing
services. Each service has an agent assigned to it (not embedded
in it). Agents are the intelligence layer; services are the
capability layer. Multi-service agents span domain boundaries.
Agent-to-agent communication through the broker.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 20:05:45 +01:00
Asim Aslam bc570d674f docs: update landing hero — describe it, run it, talk to it (#2937)
Lead with the AI-first experience instead of "write services in Go."
The entry point is now describing what you need, not writing code.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 18:51:41 +01:00
Asim Aslam e59d056f97 Update Discord invite link and enhance landing hero description (#2936)
* chore: update Discord invite link everywhere

Replace discord.gg/jwTYuUVAGh and discord.gg/go-micro with
discord.gg/WeMU5AGxD across all docs, blog posts, issue templates,
security policy, and contrib READMEs.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: update landing hero — describe it, run it, talk to it

Lead with the AI-first experience instead of "write services in Go."
The entry point is now describing what you need, not writing code.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 17:50:11 +01:00
Asim Aslam e13ef7eed5 chore: update Discord invite link everywhere (#2935)
Replace discord.gg/jwTYuUVAGh and discord.gg/go-micro with
discord.gg/WeMU5AGxD across all docs, blog posts, issue templates,
security policy, and contrib READMEs.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 13:46:30 +01:00
Asim Aslam 23f682181c Update section title from 'The Bet' to 'The next step' 2026-06-04 11:53:31 +01:00
Asim Aslam bc1092b18a Restructure README for AI experience and framework clarity (#2934)
* docs: restructure README — AI story completes before manual code

Quick Start now flows through the full AI experience: generate →
review → run → chat → grow (mid-conversation service generation).
The reader sees the complete prompt-to-production story without
interruption.

"Writing Services" is a separate section below for developers who
want to understand the framework underneath. Shows Go code, doc
comments, @example tags, micro run, and scaffolding templates.

Features table and CLI table reordered: AI first, then framework.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* blog: Going All In on AI

Post 14 — the strategic case for making AI the primary direction.
Covers the evolution from microservices framework to AI-native
platform, why the timing is right (tool calling works, MCP is real,
sponsors align), and what's not changing (framework still works,
no agent framework complexity).

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 11:52:48 +01:00
Asim Aslam 16918669ca docs: restructure README — AI story completes before manual code (#2933)
Quick Start now flows through the full AI experience: generate →
review → run → chat → grow (mid-conversation service generation).
The reader sees the complete prompt-to-production story without
interruption.

"Writing Services" is a separate section below for developers who
want to understand the framework underneath. Shows Go code, doc
comments, @example tags, micro run, and scaffolding templates.

Features table and CLI table reordered: AI first, then framework.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 11:35:57 +01:00
Asim Aslam a357d1870d Update README and landing page with new AI-native hero image (#2932)
* docs: add binary install option to README quick start

Show curl install.sh first (no Go required), go install second.
Uses the existing install script at go-micro.dev/install.sh which
downloads pre-built binaries from GitHub releases.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: regenerate hero image for new AI-native positioning

New hero shows terminal running micro run with service generation,
an AI agent orchestrating, and task/shipping/category service nodes.
Matches the "Microservices That AI Agents Can Use" headline.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: replace video with hero image on landing page

The old video autoplayed and covered the new hero image. Replace
the video element with a static img tag showing the new AI-native
hero graphic.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 11:27:21 +01:00
Asim Aslam 91a545c6f2 Enhance README with binary install option and update hero image (#2931)
* docs: add binary install option to README quick start

Show curl install.sh first (no Go required), go install second.
Uses the existing install script at go-micro.dev/install.sh which
downloads pre-built binaries from GitHub releases.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: regenerate hero image for new AI-native positioning

New hero shows terminal running micro run with service generation,
an AI agent orchestrating, and task/shipping/category service nodes.
Matches the "Microservices That AI Agents Can Use" headline.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 11:21:47 +01:00
Asim Aslam 00392aa1f2 docs: add binary install option to README quick start (#2930)
Show curl install.sh first (no Go required), go install second.
Uses the existing install script at go-micro.dev/install.sh which
downloads pre-built binaries from GitHub releases.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 11:15:40 +01:00
Asim Aslam b54507710d Revise README with new install command and examples
Updated installation command and added usage examples.
2026-06-04 11:14:40 +01:00
Asim Aslam d541625e32 docs: unify README and website around one story (#2929)
Both surfaces now lead with the same line: "Go Micro is a framework
for building microservices that AI agents can use."

README:
- Leads with prompt generation + chat (the differentiator)
- Features as a compact table instead of paragraph-per-feature
- CLI workflow table
- Removed redundant sections, tightened to ~150 lines

Website:
- Hero: "Microservices That AI Agents Can Use"
- Hero command: micro run --prompt instead of go get
- Features grid reordered: AI tools, orchestration, generation first
- First two-col section: describe/generate/run/chat story
- Architecture and DX sections follow

Both tell the same story in the same order:
1. What it is (microservices framework)
2. What makes it different (every service is an AI tool)
3. How you use it (prompt → run → chat)
4. What's underneath (registry, RPC, store — all pluggable)

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 11:13:03 +01:00
Asim Aslam 7662b26b07 syntax highlighting (#2928)
* docs: add blog post 13 to blog index

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: add syntax highlighting to blog post 13 code blocks

Add language tags (bash, go, text) to all fenced code blocks so
Rouge highlights them correctly.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-04 08:19:52 +01:00
Asim Aslam 397010a82a docs: add blog post 13 to blog index (#2927)
https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-03 22:16:06 +01:00
Asim Aslam d3c4981326 Enhance AI service generation with prompt-based architecture and logic (#2926)
goreleaser / goreleaser (push) Waiting to run
* 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
Asim Aslam 96280678ee Expose framework primitives via API gateway and MCP with auth control (#2925)
* feat: expose framework primitives via API gateway and MCP

Add registry, store, and broker as both HTTP routes and MCP tools
so AI agents and HTTP clients can inspect and operate the framework.

API gateway (/micro/* namespace):
  GET  /micro/registry         List registered services
  GET  /micro/registry/{name}  Describe a service
  GET  /micro/store            List store keys
  GET  /micro/store/{key}      Read a record
  POST /micro/store/{key}      Write a record
  POST /micro/broker/{topic}   Publish a message

MCP gateway (micro_* tool prefix):
  micro_registry_list    List services
  micro_registry_get     Describe a service
  micro_store_list       List keys
  micro_store_read       Read a record
  micro_store_write      Write a record
  micro_broker_publish   Publish a message

Framework tools use a Handler field on the MCP Tool struct for
direct dispatch (no RPC). Service tools continue to use RPC.
Rate limiters and circuit breakers are applied to framework
tools the same as service tools.

* fix: make framework internals opt-in on API and MCP gateways

Framework primitives (registry, broker, store) are now only
exposed when explicitly enabled:

API gateway:  micro api --internal
MCP gateway:  Options{Internal: true}

Off by default — user services are always exposed, framework
internals require the flag. Banner output only shows framework
routes when enabled.

* fix: always expose framework internals, gate by auth in production

Revert the --internal flag approach. Framework primitives (registry,
broker, store) are now always exposed:

- micro api: /micro/* routes always available (dev tool)
- MCP gateway: micro_* tools always registered. When Auth is
  configured (production), they require micro:admin scope.
  Without Auth (dev), they're open — same as all other tools.

This follows the existing pattern: micro run/api = dev (open),
micro server = production (auth + scopes). Framework internals
follow the same security model as user services.

Remove the Internal option from MCP Options. Remove --internal
flag from micro api.

Note: scope persistence depends on the store backend. The default
in-memory store does not survive restarts. Use MICRO_STORE=file
for persistent scopes in production.

* fix: correct DefaultStore comment — it's file-backed, not memory

* fix(server): don't recreate deleted admin user on restart

When the default admin account is deleted via the dashboard, set
a marker key (auth/.admin-deleted) in the store. On startup, skip
admin creation if the marker exists. This prevents the default
admin/micro credentials from reappearing after restart when the
user has intentionally removed them.

* fix: improve agent playground first-run UX and fix doc 404s

Agent playground:
- Add setup hint in empty state explaining how to get started
  (click Settings, enter API key, type a prompt)
- Hide hint automatically when API key is already configured
- Add all 7 providers to dropdown (was only OpenAI + Anthropic)
- Include CLI fallback suggestion (micro chat)

Docs:
- Fix .md links to .html across all doc pages — Jekyll serves
  .html files, not .md. Fixes 404s including the micro run guide.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-03 11:05:51 +01:00
Asim Aslam 69fc228c73 Enhance CLI color output and expose framework primitives via API (#2924)
* feat: expose framework primitives via API gateway and MCP

Add registry, store, and broker as both HTTP routes and MCP tools
so AI agents and HTTP clients can inspect and operate the framework.

API gateway (/micro/* namespace):
  GET  /micro/registry         List registered services
  GET  /micro/registry/{name}  Describe a service
  GET  /micro/store            List store keys
  GET  /micro/store/{key}      Read a record
  POST /micro/store/{key}      Write a record
  POST /micro/broker/{topic}   Publish a message

MCP gateway (micro_* tool prefix):
  micro_registry_list    List services
  micro_registry_get     Describe a service
  micro_store_list       List keys
  micro_store_read       Read a record
  micro_store_write      Write a record
  micro_broker_publish   Publish a message

Framework tools use a Handler field on the MCP Tool struct for
direct dispatch (no RPC). Service tools continue to use RPC.
Rate limiters and circuit breakers are applied to framework
tools the same as service tools.

* fix: make framework internals opt-in on API and MCP gateways

Framework primitives (registry, broker, store) are now only
exposed when explicitly enabled:

API gateway:  micro api --internal
MCP gateway:  Options{Internal: true}

Off by default — user services are always exposed, framework
internals require the flag. Banner output only shows framework
routes when enabled.

* fix: always expose framework internals, gate by auth in production

Revert the --internal flag approach. Framework primitives (registry,
broker, store) are now always exposed:

- micro api: /micro/* routes always available (dev tool)
- MCP gateway: micro_* tools always registered. When Auth is
  configured (production), they require micro:admin scope.
  Without Auth (dev), they're open — same as all other tools.

This follows the existing pattern: micro run/api = dev (open),
micro server = production (auth + scopes). Framework internals
follow the same security model as user services.

Remove the Internal option from MCP Options. Remove --internal
flag from micro api.

Note: scope persistence depends on the store backend. The default
in-memory store does not survive restarts. Use MICRO_STORE=file
for persistent scopes in production.

* fix: correct DefaultStore comment — it's file-backed, not memory

* fix(server): don't recreate deleted admin user on restart

When the default admin account is deleted via the dashboard, set
a marker key (auth/.admin-deleted) in the store. On startup, skip
admin creation if the marker exists. This prevents the default
admin/micro credentials from reappearing after restart when the
user has intentionally removed them.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-03 08:26:47 +01:00
Asim Aslam 5d7609027b Enhance CLI with color output and add teardown blog post (#2923)
* feat(cli): add color output to micro chat and micro api

micro chat:
- Startup banner matching micro run style: bold header, cyan
  provider/model, green dots for each discovered tool endpoint
- Cyan bold prompt (> ) instead of plain
- Yellow arrow (→) with dimmed tool name for tool calls
- Red "error:" prefix for errors
- Dimmed "(history cleared)" for reset

micro api:
- Startup banner matching micro run style: bold header, cyan
  address, colored HTTP methods (green GET, yellow POST)

Brings the CLI UX closer to what the generated terminal
screenshot depicts — color-coded, professional, readable.

* feat(cli): adopt consistent color output across all commands

Apply the same banner/output style across the remaining commands:

micro new:    bold header, cyan service name, green ✓, cyan URLs
micro build:  green ✓ checkmarks, cyan file paths
micro deploy: bold header, cyan target
micro mcp:    bold header, green dots per tool, dimmed count
micro flow:   bold header, cyan flow/topic/provider

All commands now follow the micro run/chat/api pattern:
bold header, cyan values, green status indicators, dimmed hints.

* docs: add "Tools as Services" blog post

Write blog/12 — connects the AI story back to Go Micro's original
design: services were always self-describing, named, and uniformly
callable. The path from API gateway to MCP to LLM tools is the
same pattern — read the registry, present services in a format
the consumer understands, route calls back.

Covers the access layer pattern (HTTP, web, CLI, MCP, chat),
why doc comments became functional in the AI era, and how the
framework primitives (registry, broker, store) could all become
tools using the same mechanism.

Add to blog index, link forward from blog/11.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-02 22:15:18 +01:00
Asim Aslam 5601be009a docs: add "Build Your Own AI Agent CLI" teardown blog post (#2921)
Write blog/11 — a teardown of micro chat showing how to build an
LLM tool-calling agent in ~150 lines. Walks through the four pieces:
discover tools, create the model, track conversation, run the loop.
Uses the actual chat.go source. Ends with extension ideas and a
"make it yours" framing.

Add to blog index, link forward from blog/10.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-02 12:06:22 +01:00
Asim Aslam 888dbbca4a Refactor AI tool handling and enhance CLI command documentation (#2920)
goreleaser / goreleaser (push) Waiting to run
* refactor(ai): rename ToolSet to Tools, simplify wiring with WithTools

Move tool discovery/execution fully into the ai package as ai.Tools
(formerly ai.ToolSet), and simplify the usage model:

- NewTools(reg, ai.ToolClient(c)) takes the execution client as an
  option instead of threading it through Handler(c) per call
- New ai.WithTools(tools) option wires the tool handler into a model
  in one call, replacing ai.WithToolHandler(set.Handler(c))
- ai.DiscoverTools(reg) for one-shot discovery

Before:
  set := ai.NewToolSet(reg)
  list, _ := set.Discover()
  m := ai.New(p, ai.WithToolHandler(set.Handler(client)))

After:
  tools := ai.NewTools(reg, ai.ToolClient(client))
  list, _ := tools.Discover()
  m := ai.New(p, ai.WithTools(tools))

Update ai/flow, micro chat, README, ai integration doc, Atlas Cloud
guide, and blog posts 3/8/9/10.

* feat(cli): add per-interface commands (registry, broker, store, config)

Map go-micro's core interfaces onto the CLI so the framework's
building blocks are inspectable and manipulable from the terminal:

  micro registry list/get/watch       service discovery
  micro broker publish/subscribe      pub/sub messaging
  micro store read/write/delete/list  persistence
  micro config get/dump               dynamic config (from env)

Structured pluggably in cmd/micro/resource: each interface is one
file exposing a Command() func, all wired through a commandFuncs
slice in resource.go. Adding a new resource command is a single
file plus one slice entry. Shared printJSON/fail helpers keep
output and errors consistent across commands.

Each command's verbs mirror the interface methods. Output is JSON
for structured data, raw for single values. Update README and
getting-started with an "inspecting the framework" section.

* docs: update CLI README with all new commands

Add documentation for commands that were missing from the CLI README:
- micro new --template (crud, pubsub, api)
- micro api (standalone HTTP gateway)
- micro registry list/get/watch
- micro broker publish/subscribe
- micro store read/write/delete/list
- micro config get/dump
- micro chat (interactive LLM agent)
- micro flow run/exec (event-driven orchestration)
- micro mcp serve/list/test

Organized into sections: API Gateway, Inspecting the Framework
(registry, broker, store, config), and AI & Agents (chat, flow, mcp).

* refactor(ai): move History from caller to Request field

History is now pure state (no Generate method). Instead, pass it
via Request.History and call ai.Generate(ctx, model, req):

Before:
  hist := ai.NewHistory("system prompt", 50)
  resp, _ := hist.Generate(ctx, model, prompt, tools)

After:
  hist := ai.NewHistory(50)
  resp, _ := ai.Generate(ctx, model, &ai.Request{
      Prompt:       prompt,
      SystemPrompt: "system prompt",
      Tools:        tools,
      History:      hist,
  })

The model is always the thing you call. History is context you
pass in. ai.Generate() handles the bookkeeping: prepends
accumulated messages before the call, records the exchange after.

NewHistory no longer takes a system prompt (it belongs on the
Request, where it always did).

Update micro chat, ai/flow, and all blog posts/docs.

* refactor(ai): make History a plain message accumulator

History no longer has Generate or touches the model. It's just
Add/Messages/Reset/Len with truncation — a helper for building
Request.Messages across turns.

Before:
  hist := ai.NewHistory(50)
  resp, _ := ai.Generate(ctx, m, &ai.Request{History: hist, ...})

After:
  hist := ai.NewHistory(50)
  hist.Add("user", prompt)
  resp, _ := m.Generate(ctx, &ai.Request{Messages: hist.Messages(), ...})
  hist.Add("assistant", resp.Reply)

Remove History field from Request. Remove package-level
ai.Generate(ctx, model, req) wrapper — users call m.Generate()
directly, which is the interface method. History is a convenience
for accumulating messages, not a participant in generation.

Update micro chat, ai/flow, blog posts 9 and 10.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-30 16:20:38 +01:00
Asim Aslam f48d81c760 Cli commands (#2919)
* refactor(ai): rename ToolSet to Tools, simplify wiring with WithTools

Move tool discovery/execution fully into the ai package as ai.Tools
(formerly ai.ToolSet), and simplify the usage model:

- NewTools(reg, ai.ToolClient(c)) takes the execution client as an
  option instead of threading it through Handler(c) per call
- New ai.WithTools(tools) option wires the tool handler into a model
  in one call, replacing ai.WithToolHandler(set.Handler(c))
- ai.DiscoverTools(reg) for one-shot discovery

Before:
  set := ai.NewToolSet(reg)
  list, _ := set.Discover()
  m := ai.New(p, ai.WithToolHandler(set.Handler(client)))

After:
  tools := ai.NewTools(reg, ai.ToolClient(client))
  list, _ := tools.Discover()
  m := ai.New(p, ai.WithTools(tools))

Update ai/flow, micro chat, README, ai integration doc, Atlas Cloud
guide, and blog posts 3/8/9/10.

* feat(cli): add per-interface commands (registry, broker, store, config)

Map go-micro's core interfaces onto the CLI so the framework's
building blocks are inspectable and manipulable from the terminal:

  micro registry list/get/watch       service discovery
  micro broker publish/subscribe      pub/sub messaging
  micro store read/write/delete/list  persistence
  micro config get/dump               dynamic config (from env)

Structured pluggably in cmd/micro/resource: each interface is one
file exposing a Command() func, all wired through a commandFuncs
slice in resource.go. Adding a new resource command is a single
file plus one slice entry. Shared printJSON/fail helpers keep
output and errors consistent across commands.

Each command's verbs mirror the interface methods. Output is JSON
for structured data, raw for single values. Update README and
getting-started with an "inspecting the framework" section.

* docs: update CLI README with all new commands

Add documentation for commands that were missing from the CLI README:
- micro new --template (crud, pubsub, api)
- micro api (standalone HTTP gateway)
- micro registry list/get/watch
- micro broker publish/subscribe
- micro store read/write/delete/list
- micro config get/dump
- micro chat (interactive LLM agent)
- micro flow run/exec (event-driven orchestration)
- micro mcp serve/list/test

Organized into sections: API Gateway, Inspecting the Framework
(registry, broker, store, config), and AI & Agents (chat, flow, mcp).

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-30 14:52:22 +01:00
Asim Aslam 3acf74a29a Refactor tool management and add CLI commands for interfaces (#2918)
* refactor(ai): rename ToolSet to Tools, simplify wiring with WithTools

Move tool discovery/execution fully into the ai package as ai.Tools
(formerly ai.ToolSet), and simplify the usage model:

- NewTools(reg, ai.ToolClient(c)) takes the execution client as an
  option instead of threading it through Handler(c) per call
- New ai.WithTools(tools) option wires the tool handler into a model
  in one call, replacing ai.WithToolHandler(set.Handler(c))
- ai.DiscoverTools(reg) for one-shot discovery

Before:
  set := ai.NewToolSet(reg)
  list, _ := set.Discover()
  m := ai.New(p, ai.WithToolHandler(set.Handler(client)))

After:
  tools := ai.NewTools(reg, ai.ToolClient(client))
  list, _ := tools.Discover()
  m := ai.New(p, ai.WithTools(tools))

Update ai/flow, micro chat, README, ai integration doc, Atlas Cloud
guide, and blog posts 3/8/9/10.

* feat(cli): add per-interface commands (registry, broker, store, config)

Map go-micro's core interfaces onto the CLI so the framework's
building blocks are inspectable and manipulable from the terminal:

  micro registry list/get/watch       service discovery
  micro broker publish/subscribe      pub/sub messaging
  micro store read/write/delete/list  persistence
  micro config get/dump               dynamic config (from env)

Structured pluggably in cmd/micro/resource: each interface is one
file exposing a Command() func, all wired through a commandFuncs
slice in resource.go. Adding a new resource command is a single
file plus one slice entry. Shared printJSON/fail helpers keep
output and errors consistent across commands.

Each command's verbs mirror the interface methods. Output is JSON
for structured data, raw for single values. Update README and
getting-started with an "inspecting the framework" section.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-30 14:43:09 +01:00
Asim Aslam c4b4cbef25 refactor(ai): rename ToolSet to Tools, simplify wiring with WithTools (#2917)
Move tool discovery/execution fully into the ai package as ai.Tools
(formerly ai.ToolSet), and simplify the usage model:

- NewTools(reg, ai.ToolClient(c)) takes the execution client as an
  option instead of threading it through Handler(c) per call
- New ai.WithTools(tools) option wires the tool handler into a model
  in one call, replacing ai.WithToolHandler(set.Handler(c))
- ai.DiscoverTools(reg) for one-shot discovery

Before:
  set := ai.NewToolSet(reg)
  list, _ := set.Discover()
  m := ai.New(p, ai.WithToolHandler(set.Handler(client)))

After:
  tools := ai.NewTools(reg, ai.ToolClient(client))
  list, _ := tools.Discover()
  m := ai.New(p, ai.WithTools(tools))

Update ai/flow, micro chat, README, ai integration doc, Atlas Cloud
guide, and blog posts 3/8/9/10.

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-30 14:21:35 +01:00
Asim Aslam a9421e5b7e Update logo design, add AI integration documentation and blog post (#2916)
* feat: update Go Micro logo to interconnected nodes design

Replace the text-on-blue-square logo with a modern icon: three
teal nodes connected in a triangle, representing distributed
systems. Generated via Atlas Cloud. Clean at all sizes — works
as GitHub avatar, favicon, and nav bar icon.

* feat: new logo, AI integration architecture doc, and landing page CTA

Update logo to triangle-nodes icon + "Go Micro" text wordmark.
Save icon-only variant for favicon/avatar use.

Add docs/ai-integration.md — a single page that explains how the
AI stack fits together: services → registry → MCP gateway →
ai/tools → ai.Model → micro chat. Layer-by-layer with code
examples, provider table, and "what you don't need" section.

Add AI Integration to docs sidebar navigation (after Getting
Started). Update the landing page AI section with a direct CTA
button linking to the new doc.

* fix: restore original logo and add border-radius to all renders

Revert logo to original. Add border-radius: 8px to the logo img
in the landing page nav, docs layout nav, and blog layout nav
so the square logo renders with rounded corners everywhere.
Remove unused icon.png.

* docs: add micro chat blog post

Write blog/10 — a dedicated post for micro chat covering:
- What it does (interactive LLM agent for services)
- How it works (ai/tools → ai.History → ai.Model stack)
- Multi-turn conversation examples
- All provider options and env vars
- Single prompt mode for scripting
- Why it works (registry metadata + doc comments = tool descriptions)
- Programmatic usage with the same building blocks
- Link to micro flow as the event-driven counterpart

Add to blog index. Update blog 9 nav to link forward.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-30 13:46:05 +01:00
Asim Aslam 03f912f68a Add AtlasCloud sponsor logo to README 2026-05-30 09:58:44 +01:00
Asim Aslam 594ee107b7 Clean up README.md formatting
Removed unnecessary whitespace and line breaks in README.
2026-05-30 09:58:08 +01:00
Asim Aslam 2f164595f2 Add Atlas Cloud logo link to README
Added an image link for Atlas Cloud to the README.
2026-05-30 09:49:55 +01:00
Asim Aslam 740980a9cc Clean up whitespace in README.md
Removed extra whitespace before the second image link.
2026-05-30 09:49:33 +01:00
Asim Aslam 3d2d9acd68 Fix formatting issues in README.md 2026-05-30 09:46:28 +01:00
Asim Aslam 88aa0cc666 Update logo, add AI integration docs, and enhance CLI features (#2915)
* feat: update Go Micro logo to interconnected nodes design

Replace the text-on-blue-square logo with a modern icon: three
teal nodes connected in a triangle, representing distributed
systems. Generated via Atlas Cloud. Clean at all sizes — works
as GitHub avatar, favicon, and nav bar icon.

* feat: new logo, AI integration architecture doc, and landing page CTA

Update logo to triangle-nodes icon + "Go Micro" text wordmark.
Save icon-only variant for favicon/avatar use.

Add docs/ai-integration.md — a single page that explains how the
AI stack fits together: services → registry → MCP gateway →
ai/tools → ai.Model → micro chat. Layer-by-layer with code
examples, provider table, and "what you don't need" section.

Add AI Integration to docs sidebar navigation (after Getting
Started). Update the landing page AI section with a direct CTA
button linking to the new doc.

* fix: restore original logo and add border-radius to all renders

Revert logo to original. Add border-radius: 8px to the logo img
in the landing page nav, docs layout nav, and blog layout nav
so the square logo renders with rounded corners everywhere.
Remove unused icon.png.

* feat(ai): add ai/flow package and micro flow CLI

Add ai/flow — event-driven LLM orchestration for go-micro. A Flow
subscribes to a broker topic, discovers services as tools, and
feeds each event into an LLM that decides which RPCs to call.

Key types:
- flow.New(name, opts...) creates a flow with trigger topic,
  prompt template, provider config
- flow.Register(registry, broker, client) wires it into a service
- flow.Execute(ctx, data) runs the flow once (for testing/CLI)
- flow.Results() returns execution history

Add micro flow CLI with two subcommands:
- micro flow run: subscribe to a topic and react to events
- micro flow exec: one-shot execution with inline data

Both output JSON results with flow name, prompt, tool calls,
reply, answer, duration, and errors.

Example:
  micro flow run --trigger events.user.created \
    --prompt "New user: {{.Data}}. Send welcome email." \
    --provider anthropic

  micro flow exec --prompt "List all users" --provider anthropic

* docs: update flows blog post with ai/flow package and CLI examples

Add "Update: We Built It" section to blog/9 showing the ai/flow
package API, CLI usage for both event-driven and one-shot modes,
and what it does/doesn't do. Links the conceptual discussion to
the shipped implementation.

* feat(cli): add micro api gateway command, clarify run vs server

Add 'micro api' — a standalone lightweight HTTP-to-RPC gateway:
- POST /{service}/{endpoint} proxies to RPC calls
- GET / lists all services and endpoints
- GET /{service} describes a service
- GET /health returns ok
- Supports Micro-Endpoint header for endpoint routing
- No dashboard, no auth, no hot reload — just the proxy

Update help text to clarify the three gateway modes:
- micro api: bare HTTP-to-RPC proxy
- micro run: development mode (hot reload + gateway + agent playground)
- micro server: production mode (dashboard + auth + JWT)

* docs: update README, getting started, and AI integration for all new features

Update the development workflow table in both README and getting
started to include all CLI commands: micro new --template,
micro api, micro chat, micro flow, micro call.

Getting started:
- Add CRUD template example to quick start
- Update workflow table with 8 stages
- Add AI Integration, MCP, and gRPC Interop to Next Steps

README:
- Add template flag to quick start example
- Update workflow table
- Reorder User Guides with AI Integration prominent

AI Integration doc:
- Update stack diagram to include micro api and ai/flow
- Add micro flow section with Go API and CLI examples
- Add micro api section
- Renumber layers (now 8 instead of 7)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 22:49:37 +01:00
Asim Aslam 601c67675f Update logo, add AI integration docs, and enhance CLI features (#2914)
* feat: update Go Micro logo to interconnected nodes design

Replace the text-on-blue-square logo with a modern icon: three
teal nodes connected in a triangle, representing distributed
systems. Generated via Atlas Cloud. Clean at all sizes — works
as GitHub avatar, favicon, and nav bar icon.

* feat: new logo, AI integration architecture doc, and landing page CTA

Update logo to triangle-nodes icon + "Go Micro" text wordmark.
Save icon-only variant for favicon/avatar use.

Add docs/ai-integration.md — a single page that explains how the
AI stack fits together: services → registry → MCP gateway →
ai/tools → ai.Model → micro chat. Layer-by-layer with code
examples, provider table, and "what you don't need" section.

Add AI Integration to docs sidebar navigation (after Getting
Started). Update the landing page AI section with a direct CTA
button linking to the new doc.

* fix: restore original logo and add border-radius to all renders

Revert logo to original. Add border-radius: 8px to the logo img
in the landing page nav, docs layout nav, and blog layout nav
so the square logo renders with rounded corners everywhere.
Remove unused icon.png.

* feat(ai): add ai/flow package and micro flow CLI

Add ai/flow — event-driven LLM orchestration for go-micro. A Flow
subscribes to a broker topic, discovers services as tools, and
feeds each event into an LLM that decides which RPCs to call.

Key types:
- flow.New(name, opts...) creates a flow with trigger topic,
  prompt template, provider config
- flow.Register(registry, broker, client) wires it into a service
- flow.Execute(ctx, data) runs the flow once (for testing/CLI)
- flow.Results() returns execution history

Add micro flow CLI with two subcommands:
- micro flow run: subscribe to a topic and react to events
- micro flow exec: one-shot execution with inline data

Both output JSON results with flow name, prompt, tool calls,
reply, answer, duration, and errors.

Example:
  micro flow run --trigger events.user.created \
    --prompt "New user: {{.Data}}. Send welcome email." \
    --provider anthropic

  micro flow exec --prompt "List all users" --provider anthropic

* docs: update flows blog post with ai/flow package and CLI examples

Add "Update: We Built It" section to blog/9 showing the ai/flow
package API, CLI usage for both event-driven and one-shot modes,
and what it does/doesn't do. Links the conceptual discussion to
the shipped implementation.

* feat(cli): add micro api gateway command, clarify run vs server

Add 'micro api' — a standalone lightweight HTTP-to-RPC gateway:
- POST /{service}/{endpoint} proxies to RPC calls
- GET / lists all services and endpoints
- GET /{service} describes a service
- GET /health returns ok
- Supports Micro-Endpoint header for endpoint routing
- No dashboard, no auth, no hot reload — just the proxy

Update help text to clarify the three gateway modes:
- micro api: bare HTTP-to-RPC proxy
- micro run: development mode (hot reload + gateway + agent playground)
- micro server: production mode (dashboard + auth + JWT)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 18:13:06 +01:00
Asim Aslam b97f45106d Update logo, add AI integration docs, and implement ai/flow package (#2913)
* feat: update Go Micro logo to interconnected nodes design

Replace the text-on-blue-square logo with a modern icon: three
teal nodes connected in a triangle, representing distributed
systems. Generated via Atlas Cloud. Clean at all sizes — works
as GitHub avatar, favicon, and nav bar icon.

* feat: new logo, AI integration architecture doc, and landing page CTA

Update logo to triangle-nodes icon + "Go Micro" text wordmark.
Save icon-only variant for favicon/avatar use.

Add docs/ai-integration.md — a single page that explains how the
AI stack fits together: services → registry → MCP gateway →
ai/tools → ai.Model → micro chat. Layer-by-layer with code
examples, provider table, and "what you don't need" section.

Add AI Integration to docs sidebar navigation (after Getting
Started). Update the landing page AI section with a direct CTA
button linking to the new doc.

* fix: restore original logo and add border-radius to all renders

Revert logo to original. Add border-radius: 8px to the logo img
in the landing page nav, docs layout nav, and blog layout nav
so the square logo renders with rounded corners everywhere.
Remove unused icon.png.

* feat(ai): add ai/flow package and micro flow CLI

Add ai/flow — event-driven LLM orchestration for go-micro. A Flow
subscribes to a broker topic, discovers services as tools, and
feeds each event into an LLM that decides which RPCs to call.

Key types:
- flow.New(name, opts...) creates a flow with trigger topic,
  prompt template, provider config
- flow.Register(registry, broker, client) wires it into a service
- flow.Execute(ctx, data) runs the flow once (for testing/CLI)
- flow.Results() returns execution history

Add micro flow CLI with two subcommands:
- micro flow run: subscribe to a topic and react to events
- micro flow exec: one-shot execution with inline data

Both output JSON results with flow name, prompt, tool calls,
reply, answer, duration, and errors.

Example:
  micro flow run --trigger events.user.created \
    --prompt "New user: {{.Data}}. Send welcome email." \
    --provider anthropic

  micro flow exec --prompt "List all users" --provider anthropic

* docs: update flows blog post with ai/flow package and CLI examples

Add "Update: We Built It" section to blog/9 showing the ai/flow
package API, CLI usage for both event-driven and one-shot modes,
and what it does/doesn't do. Links the conceptual discussion to
the shipped implementation.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 17:13:16 +01:00
Asim Aslam 28fa44b2ca Update logo design, enhance AI integration docs, and simplify navigation (#2912)
* feat: update Go Micro logo to interconnected nodes design

Replace the text-on-blue-square logo with a modern icon: three
teal nodes connected in a triangle, representing distributed
systems. Generated via Atlas Cloud. Clean at all sizes — works
as GitHub avatar, favicon, and nav bar icon.

* feat: new logo, AI integration architecture doc, and landing page CTA

Update logo to triangle-nodes icon + "Go Micro" text wordmark.
Save icon-only variant for favicon/avatar use.

Add docs/ai-integration.md — a single page that explains how the
AI stack fits together: services → registry → MCP gateway →
ai/tools → ai.Model → micro chat. Layer-by-layer with code
examples, provider table, and "what you don't need" section.

Add AI Integration to docs sidebar navigation (after Getting
Started). Update the landing page AI section with a direct CTA
button linking to the new doc.

* fix: restore original logo and add border-radius to all renders

Revert logo to original. Add border-radius: 8px to the logo img
in the landing page nav, docs layout nav, and blog layout nav
so the square logo renders with rounded corners everywhere.
Remove unused icon.png.

* fix: trim nav to 3 links across all layouts

Remove Reference and Home links from nav across landing page,
docs layout, and blog layout. Keep only Docs, Blog, GitHub —
the three things people actually need. Fixes crowded nav on
mobile where 5 links plus a menu button didn't fit.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 16:55:36 +01:00
Asim Aslam 985621f4b4 AI integration updates (#2911)
* feat: update Go Micro logo to interconnected nodes design

Replace the text-on-blue-square logo with a modern icon: three
teal nodes connected in a triangle, representing distributed
systems. Generated via Atlas Cloud. Clean at all sizes — works
as GitHub avatar, favicon, and nav bar icon.

* feat: new logo, AI integration architecture doc, and landing page CTA

Update logo to triangle-nodes icon + "Go Micro" text wordmark.
Save icon-only variant for favicon/avatar use.

Add docs/ai-integration.md — a single page that explains how the
AI stack fits together: services → registry → MCP gateway →
ai/tools → ai.Model → micro chat. Layer-by-layer with code
examples, provider table, and "what you don't need" section.

Add AI Integration to docs sidebar navigation (after Getting
Started). Update the landing page AI section with a direct CTA
button linking to the new doc.

* fix: restore original logo and add border-radius to all renders

Revert logo to original. Add border-radius: 8px to the logo img
in the landing page nav, docs layout nav, and blog layout nav
so the square logo renders with rounded corners everywhere.
Remove unused icon.png.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 16:30:23 +01:00
Asim Aslam 7a1ab14847 docs: rewrite Anthropic blog post with updated content and new header image (#2910)
goreleaser / goreleaser (push) Waiting to run
Rewrite blog/3 to reflect current state of the project:
- Update numbers (7 providers, image/video support, micro chat)
- Add "What Came After" section covering everything shipped since
- Tighten prose, remove stale roadmap percentages
- Replace generic MCP image with Claude-themed header generated
  via Atlas Cloud (orange AI orb connecting to service nodes)
- Streamline code examples
- Update star count and Try It section

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 15:57:39 +01:00
Asim Aslam c26d74a8a1 Add CRUD, pub/sub, and API gateway templates; update AI features (#2909)
* feat(website): redesign docs and blog layouts, add blog header images

Redesign both layouts to match the new landing page:
- Consistent nav bar with logo, Docs, Blog, GitHub, Reference, Home
- Consistent footer with copyright and links
- CSS custom properties for theming
- Updated typography, spacing, and code block styling
- Active sidebar link highlighting in docs
- Dark mode support preserved

Generate 4 blog header images via Atlas Cloud:
- blog-deploy.png for post 1 (micro deploy)
- blog-mcp.png for posts 2, 3, 7 (MCP-related)
- blog-agents-demo.png for post 4 (agents demo)
- blog-dx.png for post 5 (DX cleanup)
- Reuse data-model.png for post 6 (model package)

All 7 existing blog posts now have header images.

* fix(website): prevent horizontal scroll on mobile landing page

Add overflow-x: hidden on html and body. Set max-width: 100% and
height: auto on all section and two-col images. Add overflow:
hidden to .two-col grid. Constrain hero pre with max-width and
overflow-x. Reduce font sizes and padding at mobile breakpoint.

* feat(website): add images to remaining core doc pages

Generate 5 more images via Atlas Cloud for docs:
- registry.png: service discovery diagram
- broker.png: pub/sub message broker pattern
- transport.png: multi-transport layers (HTTP, gRPC, NATS)
- config.png: dynamic configuration from multiple sources
- observability.png: monitoring dashboard with metrics/traces

Add images to registry.md, broker.md, transport.md, config.md,
observability.md, and architecture.md. All 11 main doc pages
now have header images.

* feat: add sponsor logos to landing page, README images, and flows blog post

Add Anthropic and Atlas Cloud sponsor logos to the landing page
with links to their respective blog posts. Logos display at 0.7
opacity with hover effect.

Add architecture and MCP agent images to the GitHub README for
the Overview and MCP sections.

Write blog post 9: "From Chat to Flows" — explores the concept
of LLM-powered service orchestration. Compares micro chat's
interactive model with persistent event-driven flows, shows how
the existing building blocks (ai/tools, History, broker) could
compose into a flow engine, discusses tradeoffs vs traditional
orchestration (Step Functions, Temporal), and includes a working
15-line code example. Explicitly positions it as a concept for
community feedback, not an announcement.

* feat(website): add animated hero video to landing page

Generate a 6-second hero video via Atlas Cloud's image-to-video
API (gemini-omni-flash). Shows the microservices network diagram
animating with data flowing between nodes.

Replace the static hero image with an autoplay muted looping
video element. Falls back to the static image via poster
attribute and img fallback for browsers without video support.

* feat(ai): add VideoModel interface with Atlas Cloud provider

Add ai.VideoModel interface for video generation alongside Model
and ImageModel. Supports text-to-video and image-to-video via
VideoRequest with prompt, reference images, duration, aspect
ratio, and resolution fields.

Implement GenerateVideo for Atlas Cloud using their async API:
POST /api/v1/model/generateVideo → poll /api/v1/model/prediction.
Default model is gemini-omni-flash image-to-video. Polls every
5 seconds until completion or context cancellation.

Register Atlas Cloud as a video provider via ai.RegisterVideo.
Add 3 tests: registration, no-key error, compile-time interface
check. Update ai/README.md with VideoModel docs.

The ai package now covers all three modalities:
- Model (text) — 7 providers
- ImageModel (image) — 2 providers (Atlas Cloud, OpenAI)
- VideoModel (video) — 1 provider (Atlas Cloud)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 15:52:35 +01:00
Asim Aslam 669481224c Enhance AI features with ImageModel, History, and website updates (#2907)
* feat(cli): add CRUD, pub/sub, and API gateway templates for micro new

Add --template flag to 'micro new' with three preset templates:

- crud: CRUD service with Create/Read/Update/Delete/List, in-memory
  store with sync.RWMutex, UUID generation, pagination, and doc
  comments with @example tags for MCP tool discovery.

- pubsub: Event-driven service with Publish/Stats RPCs and a
  Subscribe method that hooks into the broker. Includes event
  types with ID, type, source, data, and timestamp.

- api: API gateway service with Health and Endpoint RPCs, an
  internal HTTP route table, and a response recorder for
  proxying requests through RPC.

All templates include MCP-ready doc comments and work with
--no-mcp. The default template (no flag) is unchanged.

Usage:
  micro new myservice --template crud
  micro new myservice --template pubsub
  micro new myservice --template api

* fix(ai): update Atlas Cloud provider to use actual API formats

Fix the Atlas Cloud image generation to use their real async API:
POST /api/v1/model/generateImage → poll /api/v1/model/prediction/{id}
instead of the OpenAI-compatible endpoint which doesn't exist.

Add Quality and OutputFormat fields to ai.ImageRequest for
provider-specific image parameters.

Update default text model from llama-3.3-70b (doesn't exist) to
deepseek-ai/DeepSeek-V3-0324 (their flagship model). Update
default image model to openai/gpt-image-2/text-to-image.

* feat(website): add AI-generated images to landing page, docs, and blog

Generate 5 images via Atlas Cloud's image API (gpt-image-2) to
elevate the website experience:

- hero.png: microservices network graph for landing page
- architecture.png: registry + broker architecture diagram
- mcp-agent.png: AI agent calling services via MCP
- developer-experience.png: terminal showing micro run/chat
- blog-atlas.png: Atlas Cloud unified API illustration

Add visual sections to the landing page with architecture,
MCP integration, and developer experience showcases. Add
images to docs index, MCP docs, and Atlas Cloud blog post.

All images resized to 1200px wide and optimized for web.
Generated using Atlas Cloud sponsor credits.

* feat(website): redesign landing page and add images to docs

Redesign the landing page from a centered card layout to a
full-width modern site with:
- Top navigation bar
- Hero section with gradient background and CTA buttons
- Full-width image showcase sections
- Two-column layout for architecture, MCP, and DX sections
- Feature grid with 6 capabilities
- Footer with links
- Responsive breakpoints for mobile

Generate 3 more images via Atlas Cloud for docs:
- getting-started.png for the getting started guide
- deployment.png for the deployment guide
- data-model.png for the data model docs

Add images to getting-started.md, model.md, and deployment.md.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-29 15:16:05 +01:00
Asim Aslam 86782e6d77 Add ImageModel interface and multi-turn conversation support (#2906)
* feat(ai): add ImageModel interface with Atlas Cloud and OpenAI support

Add ai.ImageModel interface for text-to-image generation alongside
the existing ai.Model for text. Uses the same options pattern
(WithAPIKey, WithBaseURL) and the same provider registration
system (RegisterImage/NewImage).

Implement GenerateImage for Atlas Cloud and OpenAI providers via
the OpenAI-compatible /v1/images/generations endpoint. Default
image model is gpt-image-1. Responses return images as URL,
base64, or both depending on the provider.

Update Atlas Cloud blog post and integration guide with image
generation examples. Update ai/README.md with ImageModel docs.

* fix(website): widen docs content by reducing layout max-width to 1100px

Remove the 800px max-width on .content (which left empty space on
the right) and reduce the overall .layout and footer from 1400px
to 1100px. With the 230px sidebar this gives ~830px of content
width — readable and fills the page properly on desktop.

* feat(ai): add History for multi-turn conversation state

Add ai.History — a lightweight message accumulator that tracks
user prompts, assistant replies, and tool call/result pairs
across turns. FIFO truncation when message count exceeds the
configured limit. System prompt is passed through on every
Generate call.

Wire History into micro chat so conversations are multi-turn by
default (limit 50 messages). Add 'reset' command to clear
history mid-session.

5 unit tests covering accumulation, truncation, reset, snapshot
isolation, and tool call recording.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-28 14:44:46 +01:00
Asim Aslam 1e2901ad0e feat(ai): add ImageModel interface with Atlas Cloud and OpenAI support (#2905)
goreleaser / goreleaser (push) Waiting to run
Add ai.ImageModel interface for text-to-image generation alongside
the existing ai.Model for text. Uses the same options pattern
(WithAPIKey, WithBaseURL) and the same provider registration
system (RegisterImage/NewImage).

Implement GenerateImage for Atlas Cloud and OpenAI providers via
the OpenAI-compatible /v1/images/generations endpoint. Default
image model is gpt-image-1. Responses return images as URL,
base64, or both depending on the provider.

Update Atlas Cloud blog post and integration guide with image
generation examples. Update ai/README.md with ImageModel docs.

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-28 12:21:46 +01:00
Asim Aslam 426d7e4e6c fix: align sponsor logos with fixed height and clean SVG sources (#2903)
goreleaser / goreleaser (push) Waiting to run
Use height="26" on both logos for consistent alignment. Switch
Anthropic to the Wikimedia wordmark SVG (no padding) instead of
the logo.wine version which had excessive whitespace.

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-28 11:07:38 +01:00
Asim Aslam 5968fce2d6 docs: add Atlas Cloud sponsorship blog post and integration guide (#2902)
Add blog/8 announcing Atlas Cloud as an official Go Micro sponsor.
Covers the sponsorship, Atlas Cloud's platform (300+ models, OpenAI
compatibility, enterprise compliance), and how the integration
works with the ai package, ai/tools, micro chat, and micro run.

Add guides/atlascloud-integration.md with full setup instructions:
quick start, configuration options, environment variables, model
selection, tool calling with services, and provider swapping.

Add Atlas Cloud and AI Provider guides to the docs sidebar
navigation. Add sponsorship link to README header.

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-28 11:04:04 +01:00
Asim Aslam 415b0a76c2 Fix README header formatting
Removed a redundant pipe character from the README header.
2026-05-28 10:55:54 +01:00
Asim Aslam 7ef9a60441 Update README with documentation link and cleanup
Added documentation link to the README header and removed redundant documentation line.
2026-05-28 10:53:53 +01:00
Asim Aslam be156ecb95 Adjust logo width in README
Reduce the width of the Anthropic logo in sponsors section.
2026-05-28 10:53:01 +01:00
Asim Aslam 713dabbb5a Update Anthropic logo URL in README 2026-05-28 10:52:34 +01:00
Asim Aslam bbea48da78 Add sponsors section to README
Added sponsors section with Anthropic logo to README.
2026-05-28 10:52:03 +01:00
Asim Aslam a0ad9ee566 Claude/fix issue 2893 x3rpd (#2901)
* docs: add AI provider integration guide and Supported AI Providers section

Add a step-by-step guide for AI infrastructure companies to implement
ai.Model and contribute a provider to go-micro. Covers the full
lifecycle: skeleton, tool call handling, tests, registration, and PR
checklist.

Add a "Supported AI Providers" section to the project README that lists
current providers (Anthropic, OpenAI) in a table and links to the
integration guide with a call-to-action for new providers and sponsors.

Streamline the "Adding a New Provider" section in ai/README.md to point
to the new guide instead of duplicating a full code listing.

* fix: remove nonexistent Discord link from README

* fix(website): set content container width to 800px on desktop

Move the 800px max-width from .markdown-body up to .content so
the entire content pane (not just the inner body) is sized
correctly. The container now fills up to 800px beside the sidebar.

* feat(ai): wire Atlas Cloud into server and auto-detection

Import atlascloud provider in the micro server so it is available
when running micro run / micro server. Add atlascloud to
AutoDetectProvider so --ai_base_url with an atlascloud domain
selects the right provider automatically.

* feat(ai): add Google Gemini provider

Add ai/gemini implementing ai.Model for Google's Gemini API. Uses
the native generateContent endpoint with system_instruction,
contents/parts, and functionDeclarations — not an OpenAI shim.
Default model gemini-2.5-flash, auth via x-goog-api-key header.

Wire into micro server imports and AutoDetectProvider (matches
googleapis.com and google in base URL).

Update README.md and ai/README.md with provider listing.

* feat(ai): add Groq, Mistral, and Together AI providers

Add three new OpenAI-compatible providers:

- ai/groq: ultra-fast inference, default model llama-3.3-70b-versatile
- ai/mistral: Mistral AI, default model mistral-large-latest
- ai/together: Together AI, default model Llama-3.3-70B-Instruct-Turbo

All three are wired into the micro server imports and
AutoDetectProvider. README and ai/README updated with the full
provider table.

* feat(ai): add ai/tools helper and 'micro chat' interactive agent

Extract the registry-discovery + RPC-execution loop from the web
agent playground into a reusable ai/tools package:

- tools.New(reg) creates a Set bound to a registry
- Set.Discover() walks the registry and returns []ai.Tool with
  LLM-safe (underscored) names, remembering the mapping back to
  the original dotted form
- Set.Handler(client) returns an ai.ToolHandler that resolves
  the safe name and issues the RPC

Add cmd/micro/chat — an interactive 'micro chat' REPL that uses
ai/tools to let users talk to their services through any
registered AI provider. Supports --prompt for single-shot use,
auto-detects the provider from --base_url, and falls back to the
provider's conventional env var (ANTHROPIC_API_KEY, etc).

Update README with the new command and the programmatic example.

* feat(examples): add gRPC interop example

Add examples/grpc-interop showing that any standard gRPC client can
call a go-micro service — no go-micro SDK required on the client
side. Includes:

- proto/greeter.proto with generated Go, gRPC, and micro stubs
- server/ using go-micro gRPC transport
- client/ using stock google.golang.org/grpc (no go-micro imports)
- README with Python example and explanation of how routing works

Addresses the confusion from issue #2818 where users didn't know
that go-micro gRPC services are callable by any gRPC client.

* fix: strip /api prefix from MCP routes

Change /api/mcp/tools and /api/mcp/call to /mcp/tools and
/mcp/call. MCP is a first-class feature, not a sub-path of the
API proxy. Update server routes, playground template, scopes
template, run.go output, README, CLI README, and all docs.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-26 12:19:26 +01:00
Asim Aslam f5e33317b3 Remove Micro app platform promotion from README
Removed the promotion for the Micro app platform from the README.
2026-05-24 18:17:31 +01:00
Asim Aslam 081e375f29 Add AI provider integration guide and new providers support (#2900)
* docs: add AI provider integration guide and Supported AI Providers section

Add a step-by-step guide for AI infrastructure companies to implement
ai.Model and contribute a provider to go-micro. Covers the full
lifecycle: skeleton, tool call handling, tests, registration, and PR
checklist.

Add a "Supported AI Providers" section to the project README that lists
current providers (Anthropic, OpenAI) in a table and links to the
integration guide with a call-to-action for new providers and sponsors.

Streamline the "Adding a New Provider" section in ai/README.md to point
to the new guide instead of duplicating a full code listing.

* fix: remove nonexistent Discord link from README

* fix(website): set content container width to 800px on desktop

Move the 800px max-width from .markdown-body up to .content so
the entire content pane (not just the inner body) is sized
correctly. The container now fills up to 800px beside the sidebar.

* feat(ai): wire Atlas Cloud into server and auto-detection

Import atlascloud provider in the micro server so it is available
when running micro run / micro server. Add atlascloud to
AutoDetectProvider so --ai_base_url with an atlascloud domain
selects the right provider automatically.

* feat(ai): add Google Gemini provider

Add ai/gemini implementing ai.Model for Google's Gemini API. Uses
the native generateContent endpoint with system_instruction,
contents/parts, and functionDeclarations — not an OpenAI shim.
Default model gemini-2.5-flash, auth via x-goog-api-key header.

Wire into micro server imports and AutoDetectProvider (matches
googleapis.com and google in base URL).

Update README.md and ai/README.md with provider listing.

* feat(ai): add Groq, Mistral, and Together AI providers

Add three new OpenAI-compatible providers:

- ai/groq: ultra-fast inference, default model llama-3.3-70b-versatile
- ai/mistral: Mistral AI, default model mistral-large-latest
- ai/together: Together AI, default model Llama-3.3-70B-Instruct-Turbo

All three are wired into the micro server imports and
AutoDetectProvider. README and ai/README updated with the full
provider table.

* feat(ai): add ai/tools helper and 'micro chat' interactive agent

Extract the registry-discovery + RPC-execution loop from the web
agent playground into a reusable ai/tools package:

- tools.New(reg) creates a Set bound to a registry
- Set.Discover() walks the registry and returns []ai.Tool with
  LLM-safe (underscored) names, remembering the mapping back to
  the original dotted form
- Set.Handler(client) returns an ai.ToolHandler that resolves
  the safe name and issues the RPC

Add cmd/micro/chat — an interactive 'micro chat' REPL that uses
ai/tools to let users talk to their services through any
registered AI provider. Supports --prompt for single-shot use,
auto-detects the provider from --base_url, and falls back to the
provider's conventional env var (ANTHROPIC_API_KEY, etc).

Update README with the new command and the programmatic example.

* feat(examples): add gRPC interop example

Add examples/grpc-interop showing that any standard gRPC client can
call a go-micro service — no go-micro SDK required on the client
side. Includes:

- proto/greeter.proto with generated Go, gRPC, and micro stubs
- server/ using go-micro gRPC transport
- client/ using stock google.golang.org/grpc (no go-micro imports)
- README with Python example and explanation of how routing works

Addresses the confusion from issue #2818 where users didn't know
that go-micro gRPC services are callable by any gRPC client.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-24 18:17:04 +01:00
Asim Aslam 2f78103fed Claude/fix issue 2893 x3rpd (#2899)
* docs: add AI provider integration guide and Supported AI Providers section

Add a step-by-step guide for AI infrastructure companies to implement
ai.Model and contribute a provider to go-micro. Covers the full
lifecycle: skeleton, tool call handling, tests, registration, and PR
checklist.

Add a "Supported AI Providers" section to the project README that lists
current providers (Anthropic, OpenAI) in a table and links to the
integration guide with a call-to-action for new providers and sponsors.

Streamline the "Adding a New Provider" section in ai/README.md to point
to the new guide instead of duplicating a full code listing.

* feat(ai): add Atlas Cloud provider

Add ai/atlascloud implementing ai.Model for Atlas Cloud's
OpenAI-compatible chat completions API. Registers as "atlascloud"
with default model llama-3.3-70b and base URL
https://api.atlascloud.ai. Supports tool calling via ToolHandler.

Includes 7 unit tests covering registration, defaults, init,
generate-without-key, and stream-not-implemented.

Update the Supported AI Providers table in README.md and the
Supported Providers section in ai/README.md.

* fix: remove nonexistent Discord link from README

* fix(website): remove Micro app banner and widen content to 800px

Remove the "Try Micro" promotional banner from the homepage. Set
the docs content max-width to 800px for better readability on
desktop.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-24 13:49:32 +01:00
Asim Aslam 60527e1fe8 Add AI provider integration guide and Atlas Cloud support (#2898)
* docs: add AI provider integration guide and Supported AI Providers section

Add a step-by-step guide for AI infrastructure companies to implement
ai.Model and contribute a provider to go-micro. Covers the full
lifecycle: skeleton, tool call handling, tests, registration, and PR
checklist.

Add a "Supported AI Providers" section to the project README that lists
current providers (Anthropic, OpenAI) in a table and links to the
integration guide with a call-to-action for new providers and sponsors.

Streamline the "Adding a New Provider" section in ai/README.md to point
to the new guide instead of duplicating a full code listing.

* feat(ai): add Atlas Cloud provider

Add ai/atlascloud implementing ai.Model for Atlas Cloud's
OpenAI-compatible chat completions API. Registers as "atlascloud"
with default model llama-3.3-70b and base URL
https://api.atlascloud.ai. Supports tool calling via ToolHandler.

Includes 7 unit tests covering registration, defaults, init,
generate-without-key, and stream-not-implemented.

Update the Supported AI Providers table in README.md and the
Supported Providers section in ai/README.md.

* fix: remove nonexistent Discord link from README

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-24 13:31:44 +01:00
Asim Aslam defb2786ef update AI provider documentation (#2897)
goreleaser / goreleaser (push) Waiting to run
* feat: add prometheus monitoring wrapper

Reintroduces the Prometheus metrics wrapper previously available in the
plugins repository, updated for go-micro v5. Exposes request count and
latency histograms for handlers, subscribers, and outgoing client calls
via NewHandlerWrapper, NewSubscriberWrapper, NewCallWrapper and
NewClientWrapper, labelled with service/endpoint/status.

Options cover namespace, subsystem, const labels, histogram buckets and
a custom registerer; duplicate collectors (e.g. from multiple wrappers
sharing the same config) are reused transparently via a cached
metrics bundle.

Fixes #2893

* fix(registry/etcd): clear lease/register caches on KeepAlive channel closure

When the etcd client's long-lived KeepAlive channel closes (e.g. because
the lease expired on the server side during a network partition), the
previous cleanup only removed the channel bookkeeping. The stale entries
in `leases` and `register` caused the next registerNode() heartbeat to
hit the "unchanged hash" short-circuit and skip re-registration entirely,
so the service permanently disappeared from etcd.

Extract the cleanup into handleKeepAliveClosed and also drop the cached
lease id and hash so the next heartbeat performs a full Grant+Put and
the service recovers within one RegisterInterval.

Regression introduced by #2822; fix is symmetric with the existing
synchronous KeepAliveOnce recovery path that propagates
rpctypes.ErrLeaseNotFound.

* docs: add AI provider integration guide and Supported AI Providers section

Add a step-by-step guide for AI infrastructure companies to implement
ai.Model and contribute a provider to go-micro. Covers the full
lifecycle: skeleton, tool call handling, tests, registration, and PR
checklist.

Add a "Supported AI Providers" section to the project README that lists
current providers (Anthropic, OpenAI) in a table and links to the
integration guide with a call-to-action for new providers and sponsors.

Streamline the "Adding a New Provider" section in ai/README.md to point
to the new guide instead of duplicating a full code listing.

* Update contribution guidelines in README.md

Removed Discord contact information for platform contributions.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-05-10 17:14:04 +01:00
Asim Aslam 15cc876848 Emphasize 'Micro' in README link 2026-05-10 17:01:53 +01:00
Asim Aslam d3cfb3a99a Update app platform name from 'Mu' to 'Micro' 2026-05-10 17:01:23 +01:00
Asim Aslam b1680ca2da Update app platform link from Mu.xyz to Micro 2026-05-10 16:21:41 +01:00
Asim Aslam 90f7617fac Claude/fix issue 2893 x3rpd (#2895)
* feat: add prometheus monitoring wrapper

Reintroduces the Prometheus metrics wrapper previously available in the
plugins repository, updated for go-micro v5. Exposes request count and
latency histograms for handlers, subscribers, and outgoing client calls
via NewHandlerWrapper, NewSubscriberWrapper, NewCallWrapper and
NewClientWrapper, labelled with service/endpoint/status.

Options cover namespace, subsystem, const labels, histogram buckets and
a custom registerer; duplicate collectors (e.g. from multiple wrappers
sharing the same config) are reused transparently via a cached
metrics bundle.

Fixes #2893

* fix(registry/etcd): clear lease/register caches on KeepAlive channel closure

When the etcd client's long-lived KeepAlive channel closes (e.g. because
the lease expired on the server side during a network partition), the
previous cleanup only removed the channel bookkeeping. The stale entries
in `leases` and `register` caused the next registerNode() heartbeat to
hit the "unchanged hash" short-circuit and skip re-registration entirely,
so the service permanently disappeared from etcd.

Extract the cleanup into handleKeepAliveClosed and also drop the cached
lease id and hash so the next heartbeat performs a full Grant+Put and
the service recovers within one RegisterInterval.

Regression introduced by #2822; fix is symmetric with the existing
synchronous KeepAliveOnce recovery path that propagates
rpctypes.ErrLeaseNotFound.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-20 14:55:01 +01:00
Asim Aslam 79722e0c27 feat: add prometheus monitoring wrapper (#2894)
Reintroduces the Prometheus metrics wrapper previously available in the
plugins repository, updated for go-micro v5. Exposes request count and
latency histograms for handlers, subscribers, and outgoing client calls
via NewHandlerWrapper, NewSubscriberWrapper, NewCallWrapper and
NewClientWrapper, labelled with service/endpoint/status.

Options cover namespace, subsystem, const labels, histogram buckets and
a custom registerer; duplicate collectors (e.g. from multiple wrappers
sharing the same config) are reused transparently via a cached
metrics bundle.

Fixes #2893

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-15 09:24:43 +01:00
jejefferson 49070afa8c server/grpc: improve graceful stop behavior (#2892)
* server/grpc: improve graceful stop behavior

* server/grpc: add graceful stop example and test

* examples/graceful-stop: document verification steps
2026-04-10 08:10:10 +01:00
Asim Aslam 03f4759474 Fix inline style attribute in index.html 2026-04-08 07:42:12 +01:00
Asim Aslam f6fb541ace Enhance Mu.xyz promotion with styled div
Updated the promotional text for Mu.xyz with enhanced styling.
2026-04-08 07:40:51 +01:00
Asim Aslam 1426c8f349 Update README to use emoji for Mu.xyz link 2026-04-08 07:34:54 +01:00
Asim Aslam 5aedb601ba Add Mu.xyz promotional link to README
Added a promotional link for Mu.xyz app platform.
2026-04-08 07:34:25 +01:00
Asim Aslam bd13975acf Update container width and add promotional text
Increased the maximum width of the container and added a promotional paragraph for Mu.xyz.
2026-04-08 07:33:47 +01:00
Asim Aslam 213a09276e Update default.html 2026-03-26 10:11:00 +00:00
Asim Aslam f4291957e8 Remove Blog link from index.html
Removed the Blog link from the website index.
2026-03-26 10:09:12 +00:00
Asim Aslam 07411b1ef6 Remove article on chat app from blog index
Removed an article about building a chat app from the blog.
2026-03-26 10:08:54 +00:00
Asim Aslam 544496eec6 Delete internal/website/blog/8.md 2026-03-26 10:08:26 +00:00
Asim Aslam 2e95c4c610 Remove showcase section from index.html
Removed the showcase section for Go Micro projects.
2026-03-26 10:08:01 +00:00
BombartSimon 7b785df302 feat: add connection timeout call option (#2891) 2026-03-16 13:34:24 +00:00
Asim Aslam d96f12f57b Claude/update docs roadmap f zd2 j (#2889)
* feat: add agent platform showcase and blog post

Add a complete platform example (Users, Posts, Comments, Mail) that
mirrors micro/blog, demonstrating how existing microservices become
AI-accessible through MCP with zero code changes.

Includes blog post "Your Microservices Are Already an AI Platform"
walking through real agent workflows: signup, content creation,
commenting, tagging, and cross-service messaging.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: rename handler types to drop redundant Service suffix

UserService → Users, PostService → Posts, CommentService → Comments,
MailService → Mail. Matches micro/blog naming convention.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: consolidate top-level directories, reduce framework bloat

Move internal/non-public packages behind internal/ or into their
parent packages where they belong:

- deploy/ → gateway/mcp/deploy/ (Helm charts belong with the gateway)
- profile/ → service/profile/ (preset plugin profiles are a service concern)
- scripts/ → internal/scripts/ (install script is not public API)
- test/ → internal/test/ (test harness is not public API)
- util/ → internal/util/ (internal helpers shouldn't be imported externally)

Also fixes CLAUDE.md merge conflict markers and updates project
structure documentation.

All import paths updated. Build and tests pass.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: redesign model package to match framework conventions

Rename model.Database interface to model.Model (consistent with
client.Client, server.Server, store.Store). Remove generics in
favor of interface{}-based API with reflection.

Key changes:
- model.Model interface: Register once, CRUD infers table from type
- DefaultModel + NewModel() + package-level convenience functions
- Schema registered via Register(&User{}), no per-call schema passing
- Memory implementation as default (in model package, like store)
- memory/sqlite/postgres backends updated for new interface
- protoc-gen-micro generates RegisterXModel() instead of generic factory
- All docs, blog, and README updated

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: clarify blog post 7 uses modular monolith, not multi-service

Blog post 7 demonstrated all handlers in a single process but framed
it as microservices without acknowledging the architectural difference.

- Add "A Note on Architecture" section explaining this is a modular
  monolith demo and pointing to micro/blog for multi-service
- Clarify that handlers can be broken out into separate services later
- Fix "service registry" language to match single-process reality
- Restructure "Adding MCP to Existing Services" to distinguish the
  in-process approach from registry-based gateway options
- Update closing to acknowledge both paradigms
- Fix README type names (&CommentService{} -> &Comments{}, etc.)

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: add Micro Chat to website showcase

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: github artifact release CI (#2886)

* 👷feat(ci): add artifact and docker releases

* 💚fix(ci): build issues

* 💚fix(ci): add permissions

* 💚fix(ci): multiple artifacts

* 💚fix(ci): split archives

* 💚fix(ci): cross platform list

* 🚧chore(ci): package name

* 🐛fix(script): install script extract arch

* 👷fix(ci): docker origin go-micro

* Update image reference in goreleaser configuration (#2887)

Fix wrong order `user/repo`

* Add blog post on building a chat app with Go Micro

Added a blog post detailing the development of a full chat app using Go Micro, outlining features, architecture, and lessons learned.

* docs: add blog post 8 to index, put Blog before Docs on homepage

- Add "We Built a Full Chat App in a Day" (blog/8) to blog index
- Reorder homepage links: Blog first (primary), Docs second
- Rename "Documentation" to "Docs"

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Alexander Serheyev <74361701+alex-dna-tech@users.noreply.github.com>
2026-03-07 13:00:22 +00:00
Asim Aslam 8608c15fbb Add blog post on building a chat app with Go Micro
Added a blog post detailing the development of a full chat app using Go Micro, outlining features, architecture, and lessons learned.
2026-03-07 12:49:39 +00:00
Asim Aslam 9823f6df5c Add platform showcase, blog post, and refactor project structure (#2888)
* feat: add agent platform showcase and blog post

Add a complete platform example (Users, Posts, Comments, Mail) that
mirrors micro/blog, demonstrating how existing microservices become
AI-accessible through MCP with zero code changes.

Includes blog post "Your Microservices Are Already an AI Platform"
walking through real agent workflows: signup, content creation,
commenting, tagging, and cross-service messaging.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: rename handler types to drop redundant Service suffix

UserService → Users, PostService → Posts, CommentService → Comments,
MailService → Mail. Matches micro/blog naming convention.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: consolidate top-level directories, reduce framework bloat

Move internal/non-public packages behind internal/ or into their
parent packages where they belong:

- deploy/ → gateway/mcp/deploy/ (Helm charts belong with the gateway)
- profile/ → service/profile/ (preset plugin profiles are a service concern)
- scripts/ → internal/scripts/ (install script is not public API)
- test/ → internal/test/ (test harness is not public API)
- util/ → internal/util/ (internal helpers shouldn't be imported externally)

Also fixes CLAUDE.md merge conflict markers and updates project
structure documentation.

All import paths updated. Build and tests pass.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: redesign model package to match framework conventions

Rename model.Database interface to model.Model (consistent with
client.Client, server.Server, store.Store). Remove generics in
favor of interface{}-based API with reflection.

Key changes:
- model.Model interface: Register once, CRUD infers table from type
- DefaultModel + NewModel() + package-level convenience functions
- Schema registered via Register(&User{}), no per-call schema passing
- Memory implementation as default (in model package, like store)
- memory/sqlite/postgres backends updated for new interface
- protoc-gen-micro generates RegisterXModel() instead of generic factory
- All docs, blog, and README updated

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: clarify blog post 7 uses modular monolith, not multi-service

Blog post 7 demonstrated all handlers in a single process but framed
it as microservices without acknowledging the architectural difference.

- Add "A Note on Architecture" section explaining this is a modular
  monolith demo and pointing to micro/blog for multi-service
- Clarify that handlers can be broken out into separate services later
- Fix "service registry" language to match single-process reality
- Restructure "Adding MCP to Existing Services" to distinguish the
  in-process approach from registry-based gateway options
- Update closing to acknowledge both paradigms
- Fix README type names (&CommentService{} -> &Comments{}, etc.)

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: add Micro Chat to website showcase

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-07 09:33:18 +00:00
Alexander Serheyev 28f7f53143 Update image reference in goreleaser configuration (#2887)
goreleaser / goreleaser (push) Waiting to run
Fix wrong order `user/repo`
2026-03-06 15:30:53 +00:00
Alexander Serheyev 0842431050 feat: github artifact release CI (#2886)
goreleaser / goreleaser (push) Waiting to run
* 👷feat(ci): add artifact and docker releases

* 💚fix(ci): build issues

* 💚fix(ci): add permissions

* 💚fix(ci): multiple artifacts

* 💚fix(ci): split archives

* 💚fix(ci): cross platform list

* 🚧chore(ci): package name

* 🐛fix(script): install script extract arch

* 👷fix(ci): docker origin go-micro
2026-03-06 14:49:18 +00:00
Asim Aslam 7a5d86a2a4 Claude/update docs roadmap f zd2 j (#2885)
* feat: add agent platform showcase and blog post

Add a complete platform example (Users, Posts, Comments, Mail) that
mirrors micro/blog, demonstrating how existing microservices become
AI-accessible through MCP with zero code changes.

Includes blog post "Your Microservices Are Already an AI Platform"
walking through real agent workflows: signup, content creation,
commenting, tagging, and cross-service messaging.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: rename handler types to drop redundant Service suffix

UserService → Users, PostService → Posts, CommentService → Comments,
MailService → Mail. Matches micro/blog naming convention.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: consolidate top-level directories, reduce framework bloat

Move internal/non-public packages behind internal/ or into their
parent packages where they belong:

- deploy/ → gateway/mcp/deploy/ (Helm charts belong with the gateway)
- profile/ → service/profile/ (preset plugin profiles are a service concern)
- scripts/ → internal/scripts/ (install script is not public API)
- test/ → internal/test/ (test harness is not public API)
- util/ → internal/util/ (internal helpers shouldn't be imported externally)

Also fixes CLAUDE.md merge conflict markers and updates project
structure documentation.

All import paths updated. Build and tests pass.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: redesign model package to match framework conventions

Rename model.Database interface to model.Model (consistent with
client.Client, server.Server, store.Store). Remove generics in
favor of interface{}-based API with reflection.

Key changes:
- model.Model interface: Register once, CRUD infers table from type
- DefaultModel + NewModel() + package-level convenience functions
- Schema registered via Register(&User{}), no per-call schema passing
- Memory implementation as default (in model package, like store)
- memory/sqlite/postgres backends updated for new interface
- protoc-gen-micro generates RegisterXModel() instead of generic factory
- All docs, blog, and README updated

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: clarify blog post 7 uses modular monolith, not multi-service

Blog post 7 demonstrated all handlers in a single process but framed
it as microservices without acknowledging the architectural difference.

- Add "A Note on Architecture" section explaining this is a modular
  monolith demo and pointing to micro/blog for multi-service
- Clarify that handlers can be broken out into separate services later
- Fix "service registry" language to match single-process reality
- Restructure "Adding MCP to Existing Services" to distinguish the
  in-process approach from registry-based gateway options
- Update closing to acknowledge both paradigms
- Fix README type names (&CommentService{} -> &Comments{}, etc.)

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-05 13:13:31 +00:00
Asim Aslam 8ecdf07e6b Update description of the blogging platform example 2026-03-05 12:03:26 +00:00
Asim Aslam 1bb25d6e7f Add agent platform showcase and refactor project structure (#2884)
* feat: add agent platform showcase and blog post

Add a complete platform example (Users, Posts, Comments, Mail) that
mirrors micro/blog, demonstrating how existing microservices become
AI-accessible through MCP with zero code changes.

Includes blog post "Your Microservices Are Already an AI Platform"
walking through real agent workflows: signup, content creation,
commenting, tagging, and cross-service messaging.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: rename handler types to drop redundant Service suffix

UserService → Users, PostService → Posts, CommentService → Comments,
MailService → Mail. Matches micro/blog naming convention.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: consolidate top-level directories, reduce framework bloat

Move internal/non-public packages behind internal/ or into their
parent packages where they belong:

- deploy/ → gateway/mcp/deploy/ (Helm charts belong with the gateway)
- profile/ → service/profile/ (preset plugin profiles are a service concern)
- scripts/ → internal/scripts/ (install script is not public API)
- test/ → internal/test/ (test harness is not public API)
- util/ → internal/util/ (internal helpers shouldn't be imported externally)

Also fixes CLAUDE.md merge conflict markers and updates project
structure documentation.

All import paths updated. Build and tests pass.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: redesign model package to match framework conventions

Rename model.Database interface to model.Model (consistent with
client.Client, server.Server, store.Store). Remove generics in
favor of interface{}-based API with reflection.

Key changes:
- model.Model interface: Register once, CRUD infers table from type
- DefaultModel + NewModel() + package-level convenience functions
- Schema registered via Register(&User{}), no per-call schema passing
- Memory implementation as default (in model package, like store)
- memory/sqlite/postgres backends updated for new interface
- protoc-gen-micro generates RegisterXModel() instead of generic factory
- All docs, blog, and README updated

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-05 11:21:41 +00:00
Asim Aslam b8fc0902d7 Claude/update docs roadmap f zd2 j (#2883)
* feat: add agent platform showcase and blog post

Add a complete platform example (Users, Posts, Comments, Mail) that
mirrors micro/blog, demonstrating how existing microservices become
AI-accessible through MCP with zero code changes.

Includes blog post "Your Microservices Are Already an AI Platform"
walking through real agent workflows: signup, content creation,
commenting, tagging, and cross-service messaging.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* refactor: rename handler types to drop redundant Service suffix

UserService → Users, PostService → Posts, CommentService → Comments,
MailService → Mail. Matches micro/blog naming convention.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-05 08:56:24 +00:00
Asim Aslam 524e16296b Update documentation, add agent demo, and enhance service API (#2882)
* 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>
2026-03-05 08:32:59 +00:00
Asim Aslam d91812b476 Update documentation and add multi-service support with examples (#2881)
* 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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-05 07:28:30 +00:00
Asim Aslam 76bfeae456 Claude/update docs roadmap f zd2 j (#2880)
* 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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 13:13:34 +00:00
Asim Aslam f07a49e0d9 docs: add CHANGELOG.md with structured release history (#2878)
Keep a Changelog format covering 2026.01 through current unreleased
work. Includes all MCP gateway features, CLI commands, agent SDKs,
developer experience improvements, and documentation additions.

This replaces ad-hoc blog posts as the canonical "what changed" reference.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 12:05:06 +00:00
Asim Aslam 6247b1d065 chore: move internal status docs out of top level (#2879)
Move Claude-context working documents to internal/docs/:
- CURRENT_STATUS_SUMMARY.md
- PROJECT_STATUS_2026.md
- ROADMAP_2026.md
- IMPLEMENTATION_SUMMARY.md

These are session-tracking docs, not useful to most contributors.
Top level now only has standard files: README, CHANGELOG,
CONTRIBUTING, SECURITY, CLAUDE.md, and ROADMAP.

Updated all cross-references in CLAUDE.md, ROADMAP.md, and
website docs.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 11:59:52 +00:00
Asim Aslam c800dd3729 feat: add deployment example, workflow example, and MCP benchmarks (#2877)
Docker Compose deployment example (examples/deployment/):
- docker-compose.yml with Consul, MCP gateway, Jaeger tracing
- Dockerfile and Dockerfile.gateway for multi-stage builds
- README with architecture diagram and customization guide

Cross-service workflow example (examples/mcp/workflow/):
- Inventory, Orders, Notifications services
- Shows agents orchestrating multi-step workflows from natural language
- Stock check → reserve → order → notify in a single agent conversation

MCP gateway benchmark suite (gateway/mcp/benchmark_test.go):
- ListTools: ~20μs (10 tools), ~48μs (100 tools)
- Tool lookup: ~19ns (zero-alloc, scales to 500+ tools)
- Auth inspect: ~7ns, scope check: ~16ns
- Rate limiter: ~111ns per check
- JSON encode/decode: ~1.5-2μs per tool

Updated examples README with new examples index.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 11:40:10 +00:00
Asim Aslam 870b540922 Claude/mcp dx improvements f zd2 j (#2876)
* 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

* feat: add CRUD example, error handling guide, and status updates

- CRUD contact book example (examples/mcp/crud/) with 6 operations,
  rich doc comments, @example tags, and description struct tags
- Error handling guide for writing agent-friendly error responses
  using typed errors, actionable messages, and idempotency patterns
- Updated MCP examples index, CLAUDE.md, and status summary

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 11:32:27 +00:00
Asim Aslam fad2fd7af4 Claude/update docs roadmap f zd2 j (#2875)
* 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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 11:24:33 +00:00
Asim Aslam 19892f2c67 Claude/update docs roadmap f zd2 j (#2874)
* 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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 11:19:43 +00:00
Asim Aslam d2036b880d Claude/update docs roadmap f zd2 j (#2873)
* 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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 11:13:27 +00:00
Asim Aslam cad0ff1e49 Claude/update docs roadmap f zd2 j (#2872)
* 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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 10:50:00 +00:00
Asim Aslam ffe43e0e6d Claude/update docs roadmap f zd2 j (#2871)
* 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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 10:16:17 +00:00
Asim Aslam ec9473f86f Update sponsorship information in README.md 2026-03-04 10:10:46 +00:00
Asim Aslam 4c673f61b1 Fix formatting in README.md links section 2026-03-04 10:10:18 +00:00
Asim Aslam bed94bfa95 Update sponsorship information in README
Updated sponsorship link and removed sponsor text.
2026-03-04 10:10:04 +00:00
Asim Aslam d02ff2ecfa feat: add standalone MCP gateway binary (#2870)
Add cmd/micro-mcp-gateway for production MCP gateway deployment
independent of micro run. Supports:

- Registry selection: mdns, consul, etcd (via --registry flag)
- Rate limiting per tool (--rate-limit, --rate-burst)
- JWT authentication (--auth)
- Per-tool scope requirements (--scope tool=scope1,scope2)
- Audit logging to stdout (--audit)
- Environment variable configuration for all flags
- Dockerfile for containerized deployment

Usage:
  micro-mcp-gateway --address :3000 --registry consul --registry-address consul:8500

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 10:08:09 +00:00
Asim Aslam 6d9645adce feat: polish agent playground UI (#2869)
Redesign the /agent playground with improved UX:
- Chat-focused layout with full-height message area and sticky input
- Collapsible tool call cards showing name, input, result, and timing
- Thinking indicator while waiting for agent response
- Settings panel collapsed by default (auto-opens if no API key)
- Empty state with available tools preview
- Clear chat button
- Better visual hierarchy with distinct message styles

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 09:38:04 +00:00
Asim Aslam beeaad748e Claude/update docs roadmap f zd2 j (#2868)
* feat: add LlamaIndex SDK for Go Micro services

Add LlamaIndex integration package that enables LlamaIndex agents to
discover and call Go Micro microservices through the MCP gateway.
Follows the same pattern as the existing LangChain SDK.

- GoMicroToolkit with from_gateway() factory and tool filtering
- FunctionTool integration via llama_index.core.tools
- Auth support, error handling, and retry configuration
- Examples for basic agent and RAG + microservices workflows
- Unit tests with mocked gateway responses

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* docs: update status for OTel, WebSocket, and LlamaIndex SDK completion

Reflect recently completed work in roadmap and status documents:
- Q2 progress: 85% -> 95% (WebSocket, LlamaIndex SDK done)
- Q3 progress: 40% -> 50% (OpenTelemetry integration done)
- Transports: 2 -> 3 (added WebSocket)
- Agent SDKs: 1 -> 2 (added LlamaIndex)
- Test coverage: 568 -> 1,000+ lines

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: add WithMCP convenience option, improve startup banner, and blog post

- Add mcp.WithMCP(":3000") service option for one-line MCP setup
- Improve `micro run` startup banner to show Agent playground, MCP
  tools, and WebSocket endpoints prominently
- Add blog post: "Building the AI-Native Future of Go Micro with Claude"
  covering WebSocket transport, OTel integration, LlamaIndex SDK, and
  Anthropic's Claude Max sponsorship
- Update blog index and navigation links

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 09:28:07 +00:00
Asim Aslam 076b7c37be feat: add WebSocket transport for MCP gateway (#2867)
Add bidirectional WebSocket transport at /mcp/ws using JSON-RPC 2.0
protocol (same as stdio). This enables persistent connections for
real-time AI agents that need streaming tool interactions.

New files:
- gateway/mcp/websocket.go: WebSocketTransport with connection-level
  auth, per-message auth fallback, write serialization, OTel tracing
- gateway/mcp/websocket_test.go: 14 tests covering initialize,
  tools/list, tool calls, auth (header + param), scopes, rate
  limiting, audit, concurrent requests, multiple connections,
  error handling, and connection persistence

Changes:
- gateway/mcp/mcp.go: Register /mcp/ws handler in serveHTTP
- go.mod: Added github.com/gorilla/websocket v1.5.3

Auth supports two modes:
- Connection-level: Bearer token in WebSocket upgrade request headers
- Per-message: _token field in JSON-RPC params (same as stdio)

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 08:26:09 +00:00
Asim Aslam ab6f027741 Claude/update docs roadmap f zd2 j (#2866)
* Update docs and roadmap to March 2026 with focus priorities

- ROADMAP.md: Updated from Nov 2025 to reflect Q1 completions and current state
- ROADMAP_2026.md: Updated status to March 2026, added model package as delivered
- CURRENT_STATUS_SUMMARY.md: Rewrote with March 2026 status and clear next priorities
- PROJECT_STATUS_2026.md: Added model package section, updated recommendations
- Website roadmap: Updated Q3 security status and timestamps

Key focus areas identified: documentation guides, multi-protocol MCP,
LlamaIndex SDK, and OpenTelemetry integration.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* Add CLAUDE.md and four documentation guides to fill doc gaps

- CLAUDE.md: Project guide with structure, build commands, and priorities
- ai-native-services.md: End-to-end tutorial building an MCP-enabled task service
- mcp-security.md: Production security guide (auth, scopes, rate limiting, audit)
- tool-descriptions.md: Best practices for writing Go comments that help agents
- agent-patterns.md: Six integration patterns from single-agent to event-driven
- Updated docs index with new "AI & Agents" section linking all four guides

These were the highest priority gaps identified in the roadmap analysis:
the framework has solid features that were under-documented.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* feat: add OpenTelemetry tracing to MCP gateway

Integrate OpenTelemetry spans into the MCP gateway for both HTTP and
stdio transports. Each tool call now creates a server span with rich
attributes (tool name, account ID, auth outcome, transport type).
Trace context is propagated to downstream RPC calls via metadata,
enabling end-to-end distributed tracing through Jaeger, Grafana, etc.

New files:
- gateway/mcp/otel.go: Span creation, attribute constants, metadata carrier
- gateway/mcp/otel_test.go: 8 tests covering span creation, auth denied/allowed,
  rate limiting, trace propagation, noop provider, and missing token

Changes:
- Options.TraceProvider: Optional trace.TracerProvider field
- handleCallTool (HTTP): Creates OTel spans with auth/rate-limit attributes
- handleToolsCall (stdio): Same instrumentation for stdio transport
- go.mod: Added go.opentelemetry.io/otel/sdk v1.35.0 (test dependency)

The existing MCP trace ID (UUID) is preserved for backward compatibility
and recorded as a span attribute alongside the W3C trace context.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 08:16:06 +00:00
Asim Aslam 14ec9b955f Update status docs: March 2026 progress and roadmap refinement (#2865)
* Update docs and roadmap to March 2026 with focus priorities

- ROADMAP.md: Updated from Nov 2025 to reflect Q1 completions and current state
- ROADMAP_2026.md: Updated status to March 2026, added model package as delivered
- CURRENT_STATUS_SUMMARY.md: Rewrote with March 2026 status and clear next priorities
- PROJECT_STATUS_2026.md: Added model package section, updated recommendations
- Website roadmap: Updated Q3 security status and timestamps

Key focus areas identified: documentation guides, multi-protocol MCP,
LlamaIndex SDK, and OpenTelemetry integration.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

* Add CLAUDE.md and four documentation guides to fill doc gaps

- CLAUDE.md: Project guide with structure, build commands, and priorities
- ai-native-services.md: End-to-end tutorial building an MCP-enabled task service
- mcp-security.md: Production security guide (auth, scopes, rate limiting, audit)
- tool-descriptions.md: Best practices for writing Go comments that help agents
- agent-patterns.md: Six integration patterns from single-agent to event-driven
- Updated docs index with new "AI & Agents" section linking all four guides

These were the highest priority gaps identified in the roadmap analysis:
the framework has solid features that were under-documented.

https://claude.ai/code/session_01GkduEhcrqcG45rdfYh8dAc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-04 07:33:19 +00:00
Asim Aslam a789c9e94b Update Go Micro version in README 2026-02-21 05:22:24 +00:00
Copilot e110ccb5ff Refactor model interface to high-level idiomatic Go API (#2863)
* Initial plan

* Add model package with provider abstraction interface

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add unit tests for model providers

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Refactor server to use model package abstraction

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Use strings.Contains instead of custom substring search

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add comprehensive documentation for model package

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Refactor model interface to be more idiomatic Go

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Simplify server code to use new high-level Generate API

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Update documentation for new high-level model API

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-14 18:15:07 +00:00
Copilot e3337efd81 Update 2026 roadmap to reflect Q2 completions (85% → docs only) (#2862)
* Initial plan

* Update 2026 roadmap to reflect Q2 completions (CLI exports and LangChain SDK)

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Update PROJECT_STATUS and roadmap docs to reflect Q2 85% completion

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Fix CLI integration status table to show all commands as complete

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Address code review feedback: fix duplicates and add missing metrics

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-13 17:36:25 +00:00
Copilot 13d1116dee Implement Q2 2026 roadmap: MCP CLI export commands and LangChain SDK (#2861)
* Initial plan

* Implement micro mcp docs and export commands (Q2 2026 roadmap)

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add comprehensive CLI examples and documentation for new MCP commands

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add LangChain Python SDK for Go Micro (Q2 2026 roadmap)

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Update PROJECT_STATUS to reflect LangChain SDK completion

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add implementation summary for Roadmap 2026 session

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-13 14:39:48 +00:00
Copilot 1db7903010 [WIP] Implement missing features from documentation (#2859)
* Initial plan

* Add --header and --metadata flags to micro call command

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Apply code formatting with gofmt

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add clarifying comments for dual metadata handling paths

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-13 14:20:34 +00:00
Copilot 5e1042e5ae Implement micro mcp test command (#2857)
* Initial plan

* Implement micro mcp test command

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add test for parseTool function

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Address code review feedback - simplify parseTool

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-13 14:19:41 +00:00
Copilot 0f6453488e Implement missing --service flag for micro deploy command (#2858)
* Initial plan

* Implement --service flag for micro deploy command

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Address code review feedback - optimize validation and add comments

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-13 14:19:03 +00:00
Copilot abc7e3e052 Add MCP tools registry and agent playground to README and docs navigation (#2856)
* Initial plan

* Add MCP tools registry and agent playground to README and docs navigation

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-12 17:56:02 +00:00
Asim Aslam 759ad1de50 x 2026-02-12 10:59:51 +00:00
Asim Aslam 92b9f84d79 x 2026-02-12 10:55:13 +00:00
Asim Aslam 3a605c461d x 2026-02-12 10:45:13 +00:00
Asim Aslam de615e0573 x 2026-02-12 10:34:53 +00:00
Asim Aslam 9d9968d66b scopes 2026-02-12 10:33:15 +00:00
Asim Aslam 9c3e883dff add safe names for tools 2026-02-12 10:15:57 +00:00
Asim Aslam 33e828acdd x 2026-02-12 10:11:58 +00:00
Asim Aslam a2442fa72e x 2026-02-12 10:07:20 +00:00
Asim Aslam c9a3584656 update docs 2026-02-12 10:01:26 +00:00
Asim Aslam 22fa349d5f . 2026-02-12 09:56:19 +00:00
Asim Aslam 2c7f612178 . 2026-02-12 09:55:18 +00:00
Copilot 06608d354e Add Anthropic model support to the agent (#2855)
* Initial plan

* Add MCP Playground page to web UI with tool discovery and calling

- Add playground.html template with chat-style agent prompt interface
- Add /playground route handler in server
- Add /api/mcp/tools endpoint to list available MCP tools
- Add /api/mcp/call endpoint to invoke MCP tools via RPC
- Add Playground link to sidebar navigation
- Playground auto-discovers services from registry and renders them as
  callable tools with input forms and activity logging

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add playground.html template and fix .gitignore micro pattern

Fix .gitignore pattern 'micro' -> '/micro' to only ignore root-level
binary, not paths containing 'micro' as a component.

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Address code review: use crypto/rand for trace IDs, fix var redecl, remove dup comment

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Rename Playground to Agent, fix styling, add LLM-powered prompt

- Rename /playground to /agent, move Agent link to top of sidebar menu
- Fix template styling: use existing form/input/button CSS from styles.css
  instead of inline styles and form-plain class
- Add /api/agent/settings GET/POST endpoints for model API key, model
  name, and base URL configuration (stored in server store)
- Add /api/agent/prompt POST endpoint that sends user prompt to
  OpenAI-compatible LLM API with tool definitions from registry,
  executes any tool calls via RPC, and returns results with a
  follow-up LLM summary
- Show available tools in a table using existing table styles
- Prompt section is placed above settings for primary workflow

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Address code review: handle unmarshal errors, extract system prompt, improve param descriptions

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add Anthropic model support to the agent

Support both OpenAI and Anthropic APIs in the agent prompt handler:
- Add provider selector (OpenAI/Anthropic) to settings UI and backend
- Auto-detect provider from base URL when not explicitly set
- Anthropic: use /v1/messages endpoint, x-api-key header, input_schema
  format for tools, content blocks for responses, tool_use/tool_result
  message format for follow-ups
- OpenAI: unchanged /v1/chat/completions with Bearer auth
- Default models: gpt-4o (OpenAI), claude-sonnet-4-20250514 (Anthropic)
- Provider-specific defaults for base URLs

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Remove duplicate Anthropic follow-up message construction

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-12 09:32:27 +00:00
Copilot d8269fbdfb Document MCP integration and tool scopes implementation status (#2852)
* Initial plan

* Add comprehensive project status analysis and update roadmap

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add executive summary of project status

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-12 07:24:31 +00:00
Copilot ac47a4650a MCP gateway: add per-tool scopes, tracing, rate limiting, and audit logging (#2850)
* Initial plan

* Add MCP per-tool scopes, tracing, rate limiting, and audit logging

- Add Scopes field to Tool struct for per-tool scope requirements
- Add Auth (auth.Auth) integration to Options for token inspection
- Add trace ID generation (UUID) propagated via metadata to downstream RPCs
- Add per-tool rate limiting with configurable requests/sec and burst
- Add AuditFunc callback for immutable tool-call audit records
- Extract tool scopes from registry endpoint metadata ("scopes" key)
- Update both HTTP and stdio transports with auth/trace/rate/audit
- Add comprehensive tests for all new functionality

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Revert unrelated example go.mod changes

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Remove auto-generated example go.sum files

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add WithEndpointScopes helper, gateway-level ToolScopes, and documentation

- Add server.WithEndpointScopes() for declaring per-endpoint auth scopes at
  handler registration time
- Add mcp.Options.ToolScopes for gateway-level scope overrides without
  changing individual services
- Update documented example to show WithEndpointScopes usage
- Update examples/mcp/README.md with scopes, tracing, and rate-limiting docs
- Update gateway/mcp/DOCUMENTATION.md with scopes section and FAQ
- Add tests for both new features

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Fix ToolScopes doc comment: clarify override (not merge) semantics

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Revert unrelated example go.mod/go.sum changes

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Rename ToolScopes to Scopes in MCP Options

The field name "Scopes" is more universal and consistent with how
auth scopes are used throughout go-micro. Updated all code references,
tests, and documentation.

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* MCP gateway: add per-tool scopes, tracing, rate limiting, and audit logging

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-11 21:01:31 +00:00
asim f1cba0d617 update index 2026-02-11 15:30:35 +00:00
asim c658126b28 update index 2026-02-11 15:28:16 +00:00
asim 0d69e24a24 further mcp integrations 2026-02-11 14:29:26 +00:00
asim fe76f3ddb5 further mcp integrations 2026-02-11 14:12:21 +00:00
asim 3986738e2c stdio MCP transport and gateway refactor
Implement Q2 2026 roadmap items for AI-native microservices:

MCP stdio transport:
- JSON-RPC 2.0 over stdio for Claude Code integration
- Methods: initialize, tools/list, tools/call
- Auto-detection: stdio (no address) vs HTTP/SSE (with address)

micro mcp command:
- 'micro mcp serve' - start MCP server (stdio or HTTP)
- 'micro mcp list' - list available tools
- 'micro mcp test' - test a tool (placeholder)
- Enables Claude Code users to add microservices as tools

Gateway refactor:
- Created gateway/api package (reusable, 150 lines)
- Moved gateway logic from cmd/micro/server/gateway.go
- HandlerRegistrar pattern for flexibility
- cmd/micro/server/gateway.go now compatibility wrapper (72 lines)
- 50% code reduction, better separation of concerns
- Library users can now use gateway in custom apps

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 13:38:27 +00:00
asim e58d51c3ef update version in readme 2026-02-11 13:15:16 +00:00
asim bed7c4cc57 fix tests 2026-02-11 12:59:18 +00:00
asim e7335f945a noop auth fixed 2026-02-11 11:46:02 +00:00
asim 46e9940443 new 2026 roadmap 2026-02-11 11:37:14 +00:00
asim c9e582b966 go fmt 2026-02-11 11:25:43 +00:00
asim 7da9e58c81 fully functioning auth 2026-02-11 11:25:36 +00:00
Asim Aslam b1c63fa4ef Add MCP Integration section to README 2026-02-11 11:13:06 +00:00
asim e311586bd2 update mcp doc location 2026-02-11 11:09:04 +00:00
asim bc9d8c9a2b update mcp doc location 2026-02-11 11:03:13 +00:00
asim e2e0a9126f update mcp doc location 2026-02-11 11:00:49 +00:00
asim 4acb55733d update mcp doc location 2026-02-11 10:59:50 +00:00
asim 42efe1862a fix mcp exampl 2026-02-11 10:46:47 +00:00
asim 8d0180aef1 v5.15.0: Unified Gateway Architecture + MCP Support
Major Features:
- Unified gateway architecture (micro run + micro server use same code)
- MCP (Model Context Protocol) integration as library package
- AI-accessible microservices with 3 lines of code

Gateway Unification:
- Created reusable gateway module (cmd/micro/server/gateway.go)
- Updated micro run to use unified gateway (removed duplicate code)
- Conditional authentication (disabled in dev, required in prod)
- Reduced code duplication, simplified maintenance

MCP Integration:
- New library package: gateway/mcp
- Automatic service discovery → MCP tools
- HTTP/SSE transport support (stdio coming soon)
- Works for both library users and CLI users
- CLI flags: --mcp-address for micro run and micro server

Documentation:
- ADR-010: Unified Gateway Architecture
- CLI & Gateway Guide for users
- MCP Gateway README and examples
- Blog post: Making Your Microservices AI-Native with MCP

Breaking Changes: None (fully backward compatible)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 10:43:14 +00:00
asim ee76eb6d2c v5.15.0: Unified Gateway Architecture + MCP Support
Major Features:
- Unified gateway architecture (micro run + micro server use same code)
- MCP (Model Context Protocol) integration as library package
- AI-accessible microservices with 3 lines of code

Gateway Unification:
- Created reusable gateway module (cmd/micro/server/gateway.go)
- Updated micro run to use unified gateway (removed duplicate code)
- Conditional authentication (disabled in dev, required in prod)
- Reduced code duplication, simplified maintenance

MCP Integration:
- New library package: gateway/mcp
- Automatic service discovery → MCP tools
- HTTP/SSE transport support (stdio coming soon)
- Works for both library users and CLI users
- CLI flags: --mcp-address for micro run and micro server

Documentation:
- ADR-010: Unified Gateway Architecture
- CLI & Gateway Guide for users
- MCP Gateway README and examples
- Blog post: Making Your Microservices AI-Native with MCP

Breaking Changes: None (fully backward compatible)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 10:40:48 +00:00
Copilot 8d7eb01fb3 Add hosting.md documentation for go-micro services (#2848)
* Initial plan

* Add hosting.md documentation for go-micro services hosting options

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-11 10:10:05 +00:00
asim a38d7df106 go fmt 2026-02-04 14:37:40 +00:00
asim f9ba48897a fix build 2026-02-04 14:37:29 +00:00
Asim Aslam 547507b1a2 x 2026-02-04 14:14:41 +00:00
Asim Aslam 3bf02c634c x 2026-02-04 14:14:14 +00:00
Asim Aslam bab115a0bf dev UX optimisations 2026-02-04 14:12:59 +00:00
Asim Aslam 29ea3a21d6 update docs for dev UX 2026-02-04 14:01:16 +00:00
Asim Aslam bce53ce15e move all docs 2026-02-04 13:57:33 +00:00
Asim Aslam b867e490a0 fix docs reference points 2026-02-04 13:55:43 +00:00
Asim Aslam 48da4d3559 Removing genai as not relevant to microservices. 2026-02-04 13:42:59 +00:00
Asim Aslam 0cb85bf103 Add Discord link to README
Added Discord link to the README for community engagement.
2026-02-04 13:25:22 +00:00
Copilot a100a47340 Fix google.protobuf.Any JSON marshaling missing @type field (#2845)
* Initial plan

* Update JSON codec to use modern protojson for proper Any type support

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add comprehensive tests for google.protobuf.Any JSON marshaling

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Revert codec/proto to old protobuf package for backward compatibility

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-04 09:33:27 +00:00
Copilot 4ba40ea579 Replace custom logger with log/slog (#2844)
* Initial plan

* Replace custom logger with slog implementation

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Fix linting issues in slog implementation

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Address code review feedback: fix locking and use copyFields

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Restore debug/log buffer functionality with slog

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Address code review feedback: extract helper and remove dead code

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-03 15:55:46 +00:00
Copilot 50ce1a5e83 TLS certificate verification: opt-in security to preserve backward compatibility (#2843)
* Initial plan

* Fix insecure TLS configuration - make secure by default

- Changed util/tls/Config() to be secure by default (InsecureSkipVerify=false)
- Added MICRO_TLS_INSECURE=true environment variable for development/testing
- Updated documentation to emphasize security-first approach
- Added comprehensive tests for TLS configuration
- All existing broker tests pass

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Revert to backward-compatible TLS defaults to avoid breaking changes

- Reverted default to InsecureSkipVerify=true for backward compatibility
- Changed environment variable to MICRO_TLS_SECURE=true (opt-in security)
- Added deprecation warning that logs once per process
- Updated tests to reflect backward-compatible behavior
- Added comprehensive migration guide
- No breaking changes - production systems safe to upgrade
- Security improvement is opt-in via environment variable
- Planned breaking change for v6 with proper major version bump

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add TLS security update documentation

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-03 15:53:03 +00:00
Copilot 3094947953 [WIP] Remove reflect usage and improve performance (#2842)
* Initial plan

* Add comprehensive analysis documents on reflection usage

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Fix performance numbers for consistency

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add evaluation summary for reflection removal analysis

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-03 15:34:46 +00:00
Copilot 75e32f4d87 Implement NATS connection pooling and fix connection leaks (#2840)
* Initial plan

* Implement NATS connection pool with configuration options

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Implement connection pool for transport/nats

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Fix connection leaks in events/natsjs and config/source/nats

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Fix race condition in connection pool lastUsed field access

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Remove unused maxIdle field from connection pools

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-03 11:43:45 +00:00
Copilot adc90b4d2d Apply rate limiting before singleflight to prevent goroutine blocking on etcd timeout (#2841)
* Initial plan

* Apply rate limiting before singleflight to prevent blocking

- Check rate limiting BEFORE entering singleflight
- If rate-limited AND stale cache exists, return stale cache immediately
- This prevents all goroutines from blocking when etcd is down/slow
- Maintains stampede prevention via singleflight for non-rate-limited requests
- All existing tests pass

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Fix variable shadowing in rate limiting check

- Rename shadowed variables to currentLastRefresh and currentMinimumRetryInterval
- Improves code clarity and prevents potential bugs
- All tests still pass

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-02-03 11:35:34 +00:00
Copilot 87cf988e03 Fix go install @latest failures by documenting specific version (#2839)
* Initial plan

* Update documentation to use @v5.13.0 instead of @latest for go install commands

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add explanatory notes about version pinning in documentation

Co-authored-by: asim <17530+asim@users.noreply.github.com>

* Add consistent explanatory notes across all documentation files

Co-authored-by: asim <17530+asim@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: asim <17530+asim@users.noreply.github.com>
2026-01-29 10:19:55 +00:00
Asim Aslam 109ff2169a Add blog link to homepage (#2837)
Link to /blog/ from the main navigation, replacing the badge link.

Co-authored-by: Shelley <shelley@exe.dev>
2026-01-27 14:08:32 +00:00
Shelley 82b7fdbec4 Add install.sh to website for curl install
Co-authored-by: Shelley <shelley@exe.dev>
2026-01-27 14:02:38 +00:00
Shelley fea8c911be Fix blog post markdown rendering
Co-authored-by: Shelley <shelley@exe.dev>
2026-01-27 13:54:31 +00:00
Shelley cf9629c41f Add blog section with first post: Introducing micro deploy
- /blog/ - Blog index page
- /blog/1 - First post announcing micro deploy
- /docs/deployment.md - Deployment guide in website docs
- Updated navigation to include Blog link
- New blog layout template

Co-authored-by: Shelley <shelley@exe.dev>
2026-01-27 13:52:09 +00:00
Asim Aslam a5bef7af29 Add systemd-based deployment support (#2836)
* Add systemd-based deployment support

- micro init --server: Initialize server to receive deployments
  - Creates /opt/micro/{bin,data,config} directories
  - Generates systemd template unit (micro@.service)
  - Creates 'micro' system user

- micro deploy: Deploy services via SSH + systemd
  - Builds linux/amd64 binaries automatically
  - Copies via rsync/scp to server
  - Manages services via systemctl
  - Helpful error messages for common issues

- micro status --remote: Check remote service status
- micro logs --remote: Stream remote logs via journalctl
- micro stop --remote: Stop services on remote server

- Config: Added 'deploy' blocks to micro.mu for named targets

The deployment model:
- systemd is the process supervisor (battle-tested)
- SSH is the transport (standard, secure)
- No custom daemons or platforms needed

Co-authored-by: Shelley <shelley@exe.dev>

* Add deployment documentation

- docs/deployment.md: Comprehensive guide for server deployment
- README.md: Updated deployment section with full workflow

Co-authored-by: Shelley <shelley@exe.dev>

* Add deployment section to CLI documentation

Co-authored-by: Shelley <shelley@exe.dev>

* Fix systemd template escaping and rsync permission warnings

- Fix %i escaping in systemd template (was being interpreted by fmt.Sprintf)
- Handle rsync exit code 23/24 gracefully (metadata permission warnings)
- Add --omit-dir-times to rsync to avoid directory timestamp errors

Co-authored-by: Shelley <shelley@exe.dev>

* Add install script for micro CLI

Co-authored-by: Shelley <shelley@exe.dev>

* Fix non-constant format string in deploy error

Co-authored-by: Shelley <shelley@exe.dev>

---------

Co-authored-by: Shelley <shelley@exe.dev>
2026-01-27 13:27:59 +00:00
Asim Aslam 239dbfc27e fix: make build/deploy Go-native, Docker optional (#2835)
micro build:
  - Default: builds Go binaries to ./bin/
  - Cross-compile with --os and --arch
  - Docker is optional via --docker flag

micro deploy:
  - Requires --ssh user@host
  - Copies pre-built binaries (if ./bin/ exists)
  - Or syncs source and builds on remote
  - No Docker dependency

Go binaries are self-contained. No runtime needed.

Co-authored-by: Shelley <shelley@exe.dev>
2026-01-27 12:47:07 +00:00
Asim Aslam de2b3031f3 feat: add micro build and micro deploy commands (#2834)
micro build:
  - Generates Dockerfiles for services (if not present)
  - Builds container images for all services in micro.mu
  - Supports --tag, --registry, --push flags
  - --compose flag generates docker-compose.yml

micro deploy:
  - Default: deploys with docker-compose
  - --ssh user@host: deploys via SSH (rsync + build on remote)
  - --build: rebuild images before deploying

Complete workflow:
  micro run          # Develop locally
  micro build        # Build images
  micro deploy       # Deploy

Or for simple SSH deploys:
  micro deploy --ssh user@host

Co-authored-by: Shelley <shelley@exe.dev>
2026-01-27 12:40:04 +00:00
740 changed files with 62485 additions and 5479 deletions
+31
View File
@@ -0,0 +1,31 @@
# EditorConfig for go-micro
# https://editorconfig.org
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.go]
indent_style = tab
indent_size = 4
[*.{yml,yaml}]
indent_style = space
indent_size = 2
[*.{json,proto}]
indent_style = space
indent_size = 2
[*.md]
trim_trailing_whitespace = false
indent_style = space
indent_size = 2
[Makefile]
indent_style = tab
+1
View File
@@ -1 +1,2 @@
github: asim
custom: ["https://go-micro.dev/support"]
+14 -7
View File
@@ -26,19 +26,26 @@ A clear and concise description of what you expected to happen.
## Environment
- Go Micro version: [e.g. v5.3.0]
- Go version: [e.g. 1.21.0]
- OS: [e.g. Ubuntu 22.04]
- Plugins used: [e.g. consul registry, nats broker]
- Go version: [run `go version`]
- OS/Platform: [e.g. Ubuntu 22.04, macOS 14, Docker]
- Plugins/Integrations: [e.g. consul registry, nats broker, redis cache]
## Logs
```
Paste relevant logs here
Paste relevant logs here (use -v flag for verbose output)
```
## Checklist
- [ ] I've searched existing issues and this is not a duplicate
- [ ] I've provided a minimal code sample that reproduces the issue
- [ ] I've included my environment details
- [ ] I've checked the documentation
## Additional context
Add any other context about the problem here.
## Resources
- [Documentation](https://github.com/micro/go-micro/tree/master/internal/website/docs)
- [Examples](https://github.com/micro/go-micro/tree/master/internal/website/docs/examples)
## Helpful Resources
- [Troubleshooting Guide](https://github.com/micro/go-micro/tree/master/internal/website/docs/getting-started.md)
- [Examples](https://github.com/micro/go-micro/tree/master/examples)
- [API Reference](https://pkg.go.dev/go-micro.dev/v5)
- [Discord Community](https://discord.gg/WeMU5AGxD)
@@ -0,0 +1,23 @@
---
name: Commercial Support / Consulting
about: Inquire about paid support, consulting, training, or a retainer
title: '[SUPPORT] '
labels: commercial-support
assignees: asim
---
## What are you building?
A short description of your project and how you're using (or planning to use) Go Micro.
## What do you need?
- [ ] Production support / retainer (priority fixes, direct line, response SLA)
- [ ] Consulting (integration, architecture, agent design)
- [ ] Training / onboarding for a team
- [ ] Sponsored feature or fix
- [ ] Not sure yet — let's talk
## Scale & timeline
Team size, where you're running it, and any timeline that matters.
## Anything else?
Links, context, constraints. For anything you'd rather keep private, become a [sponsor](https://github.com/sponsors/asim) and message directly.
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: 💖 Sponsor Go Micro
url: https://github.com/sponsors/asim
about: Fund ongoing development and see your name or logo on the project.
- name: 📖 Documentation
url: https://go-micro.dev/docs
about: Guides, examples, and the full reference.
+17 -5
View File
@@ -18,13 +18,25 @@ A clear and concise description of any alternative solutions or features you've
## Use case
Describe how this feature would be used in practice. What problem does it solve?
**Example:**
```go
// Show how the feature would be used
```
## Implementation ideas (optional)
If you have thoughts on how this could be implemented, share them here.
## Additional context
Add any other context, code examples, or screenshots about the feature request here.
## Willing to contribute?
- [ ] I'd be willing to submit a PR for this feature
## Checklist
- [ ] I've searched existing issues and this is not a duplicate
- [ ] I've checked the roadmap and this isn't already planned
- [ ] I've provided a clear use case
- [ ] I'd be willing to submit a PR for this feature (optional)
## Resources
- [Documentation](https://github.com/micro/go-micro/tree/master/internal/website/docs)
- [Plugins](https://github.com/micro/go-micro/tree/master/internal/website/docs/plugins.md)
## Helpful Resources
- [Roadmap](https://github.com/micro/go-micro/blob/master/ROADMAP.md)
- [Contributing Guide](https://github.com/micro/go-micro/blob/master/CONTRIBUTING.md)
- [Architecture Docs](https://github.com/micro/go-micro/tree/master/internal/website/docs/architecture.md)
- [Discord Community](https://discord.gg/WeMU5AGxD)
+61
View File
@@ -0,0 +1,61 @@
---
name: Performance issue
about: Report a performance problem or regression
title: '[PERFORMANCE] '
labels: performance
assignees: ''
---
## Performance Issue
**Symptom:**
Describe the performance problem (e.g., high latency, memory leak, CPU usage)
**Expected Performance:**
What performance did you expect?
## Benchmarks
Please provide benchmarks or profiling data:
```bash
# CPU profiling
go test -cpuprofile=cpu.prof -bench=.
# Memory profiling
go test -memprofile=mem.prof -bench=.
# Results
```
**Before/After comparison (if applicable):**
- Before: X req/sec, Y ms latency
- After: X req/sec, Y ms latency
## Code Sample
```go
// Minimal code that demonstrates the performance issue
```
## Environment
- Go Micro version: [e.g. v5.3.0]
- Go version: [run `go version`]
- Hardware: [e.g. 4 CPU, 8GB RAM]
- OS: [e.g. Ubuntu 22.04]
- Load: [e.g. 1000 req/sec, 100 concurrent connections]
## Profiling Data
Attach pprof profiles if available:
- CPU profile
- Memory profile
- Goroutine dump
## Additional Context
Add any other context about the performance issue.
## Resources
- [Performance Guide](https://github.com/micro/go-micro/tree/master/internal/website/docs/performance.md)
- [Benchmarking](https://pkg.go.dev/testing#hdr-Benchmarks)
+42
View File
@@ -0,0 +1,42 @@
name: Auto-merge Codex PRs
# Part of the autonomous improvement loop (internal/docs/CONTINUOUS_IMPROVEMENT.md).
# Merges Codex's PRs once CI is green — no human involvement; CI (build, test,
# golangci-lint, harnesses) is the only gate. Scoped to PRs that are BOTH
# codex-labelled AND from a codex/* branch, so nothing else can auto-merge.
on:
schedule:
- cron: "*/15 * * * *" # sweep every 15 min
workflow_dispatch: {}
permissions:
contents: write
pull-requests: write
concurrency:
group: auto-merge-codex
cancel-in-progress: false
jobs:
merge:
runs-on: ubuntu-latest
steps:
- name: Merge green Codex PRs
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: |
gh pr list --repo "$REPO" --label codex --state open \
--json number,headRefName \
--jq '.[] | select(.headRefName | startswith("codex/")) | .number' \
| while read -r pr; do
[ -z "$pr" ] && continue
if gh pr checks "$pr" --repo "$REPO" >/dev/null 2>&1; then
echo "Checks green on #$pr — merging."
gh pr merge "$pr" --repo "$REPO" --squash --delete-branch \
|| echo "skip #$pr (not mergeable — conflicts?)"
else
echo "skip #$pr (checks pending/failing)"
fi
done
@@ -0,0 +1,62 @@
name: Continuous Improvement
# Durable backbone for the autonomous improvement loop
# (see internal/docs/CONTINUOUS_IMPROVEMENT.md).
#
# A Claude Max subscription provides no API key for CI, so the loop is driven by
# Codex rather than Claude Code: on a cadence this opens a fresh tracking issue and
# posts an @codex instruction on it, and Codex runs one improvement increment + opens
# a PR. (See the per-issue rationale below.)
#
# Codex does NOT respond to comments authored by the github-actions bot, so the
# dispatch is GATED on a CODEX_TRIGGER_TOKEN secret (a PAT for a user account Codex
# follows). Until that secret is set the workflow runs but no-ops — this avoids
# piling up @codex comments that Codex silently ignores. The moment the secret is
# added the loop activates with no further change.
#
# Each run opens a FRESH issue and dispatches Codex there, rather than re-commenting
# on one tracker issue. Codex derives its PR branch name from the triggering issue's
# context, so repeated dispatches on a single issue all collapse onto one branch name
# (codex/github-mention-<that-issue-slug>) — the first increment opens a PR, the rest
# collide on the occupied branch and silently fail to open one. A unique issue per
# run gives each increment its own branch and a clean PR. The dispatch asks Codex to
# "Closes #<issue>" so each tracking issue auto-closes when its PR merges.
on:
workflow_dispatch: {}
schedule:
- cron: "29 * * * *" # hourly, off-minute (tune as needed)
permissions:
issues: write
concurrency:
group: continuous-improvement
cancel-in-progress: false
jobs:
dispatch:
runs-on: ubuntu-latest
steps:
- name: Open a fresh increment issue and dispatch Codex
env:
GH_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN || github.token }}
HAS_TRIGGER_TOKEN: ${{ secrets.CODEX_TRIGGER_TOKEN != '' }}
REPO: ${{ github.repository }}
RUN_NUMBER: ${{ github.run_number }}
run: |
if [ "$HAS_TRIGGER_TOKEN" != "true" ]; then
echo "CODEX_TRIGGER_TOKEN is not set — skipping dispatch."
echo "Codex ignores comments from the github-actions bot, so posting now"
echo "would only create noise. Add a CODEX_TRIGGER_TOKEN secret (a PAT for"
echo "a user account Codex follows) to activate the loop."
exit 0
fi
# A unique issue per run → Codex derives a unique branch → no collisions.
ISSUE_URL=$(gh issue create --repo "$REPO" \
--title "Continuous improvement increment #$RUN_NUMBER" \
--body "Autonomous continuous-improvement increment. North Star: internal/docs/THESIS.md; charter: internal/docs/CONTINUOUS_IMPROVEMENT.md. Tracker: #3024.")
ISSUE_NUM="${ISSUE_URL##*/}"
echo "Opened issue #$ISSUE_NUM — dispatching Codex."
gh issue comment "$ISSUE_NUM" --repo "$REPO" --body \
"@codex Run one continuous-improvement increment per internal/docs/CONTINUOUS_IMPROVEMENT.md, aligned to the North Star in internal/docs/THESIS.md (the holistic services → agents → workflows lifecycle). Pick the single highest-value roadmap/issue/improvement-radar item that advances that thesis, implement it, and verify \`go build ./...\`, \`go test ./...\`, and \`golangci-lint run ./...\`. Then open the PR YOURSELF from the shell — do NOT use the make_pr tool (in this environment it only records metadata and never creates a PR). Run \`git push -u origin HEAD\` then \`gh pr create --base master --title \"<title>\" --body \"<body, including 'Closes #$ISSUE_NUM'>\"\`; the gh CLI is installed and authenticated and origin points to $REPO. One concern per PR; stay out of brand/positioning copy and breaking public API."
+59
View File
@@ -0,0 +1,59 @@
name: Harness (E2E)
# Runs the end-to-end harnesses for agents, services, flows, and provider
# conformance. The default job uses deterministic mock LLMs and needs no
# secrets. A second job runs the same harnesses against any live providers
# whose API key secrets are configured.
on:
push:
branches: ["**"]
pull_request:
branches: ["**"]
schedule:
- cron: "17 6 * * *" # daily, so the world is exercised even without changes
workflow_dispatch:
jobs:
harness:
name: Harnesses (mock LLM)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
cache: true
- name: Build
run: go build ./...
- name: Universe end-to-end (asserts; exits non-zero on failure)
run: go run ./internal/harness/universe
- name: Agent-flow harness
run: go run ./internal/harness/agent-flow
- name: Plan-delegate harness
run: go run ./internal/harness/plan-delegate
harness-live:
name: Provider harnesses (live LLM, if keys present)
runs-on: ubuntu-latest
# Only on the daily schedule or a manual run — never automatically on
# every push/PR, so changes don't quietly burn API credits. Trigger it
# by hand (Actions → Harness → Run workflow) when changing the agent,
# flow, or AI internals and you want a real-model check.
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: stable
cache: true
- name: Provider conformance against configured live models
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
TOGETHER_API_KEY: ${{ secrets.TOGETHER_API_KEY }}
ATLASCLOUD_API_KEY: ${{ secrets.ATLASCLOUD_API_KEY }}
run: go run ./internal/harness/provider-conformance
+30
View File
@@ -0,0 +1,30 @@
name: Lint
on:
push:
branches:
- "**"
pull_request:
types:
- opened
- reopened
- synchronize
branches:
- "**"
jobs:
golangci:
name: golangci-lint
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: 1.24
check-latest: true
cache: true
- name: golangci-lint
uses: golangci/golangci-lint-action@v8
with:
version: v2.5.0
+51
View File
@@ -0,0 +1,51 @@
name: goreleaser
on:
push:
tags:
- 'v*.*.*'
permissions:
contents: write
id-token: write
packages: write
attestations: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
-
name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
-
name: Set up Go
uses: actions/setup-go@v5
with:
go-version: stable
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
-
name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
-
name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v7
with:
distribution: goreleaser
version: '~> v2'
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+29 -1
View File
@@ -1,8 +1,11 @@
# Develop tools
/.vscode/
/.idea/
/.trunk
# VS Code workspace files (keep settings for consistency)
/.vscode/*
!/.vscode/settings.json
# Binaries for programs and plugins
*.exe
*.exe~
@@ -30,6 +33,7 @@ _cgo_export.*
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
coverage.html
# vim temp files
*~
@@ -39,3 +43,27 @@ _cgo_export.*
# go work files
go.work
go.work.sum
# Build artifacts
dist/
bin/
# Example binaries (go build in examples/)
examples/**/server/server
examples/**/client/client
examples/mcp/documented/documented
examples/mcp/hello/hello
# IDE-specific files
.DS_Store
/micro
# Built example/harness binaries (go build ./path/... drops these at repo root)
/plan-delegate
/agent-plan-delegate
/micro-mcp-gateway
# Local Jekyll / Bundler artifacts
internal/website/.bundle/
internal/website/_site/
internal/website/.jekyll-cache/
+57 -245
View File
@@ -1,251 +1,63 @@
# This file contains all available configuration options
# with their default values.
version: "2"
# options for analysis running
run:
# go: '1.18'
# default concurrency is a available CPU number
# concurrency: 4
# timeout for analysis, e.g. 30s, 5m, default is 1m
deadline: 10m
# exit code when at least one issue was found, default is 1
issues-exit-code: 1
# include test files or not, default is true
timeout: 5m
tests: true
# which files to skip: they will be analyzed, but issues from them
# won't be reported. Default value is empty list, but there is
# no need to include all autogenerated files, we confidently recognize
# autogenerated files. If it's not please let us know.
skip-files:
[]
# - .*\\.pb\\.go$
allow-parallel-runners: true
# list of build tags, all linters use it. Default is empty list.
build-tags: []
# output configuration options
output:
# Format: colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions
#
# Multiple can be specified by separating them by comma, output can be provided
# for each of them by separating format name and path by colon symbol.
# Output path can be either `stdout`, `stderr` or path to the file to write to.
# Example: "checkstyle:report.json,colored-line-number"
#
# Default: colored-line-number
format: colored-line-number
# Print lines of code with issue.
# Default: true
print-issued-lines: true
# Print linter name in the end of issue text.
# Default: true
print-linter-name: true
# Make issues output unique by line.
# Default: true
uniq-by-line: true
# Add a prefix to the output file references.
# Default is no prefix.
path-prefix: ""
# Sort results by: filepath, line and column.
sort-results: true
# all available settings of specific linters
linters-settings:
wsl:
allow-cuddle-with-calls: ["Lock", "RLock", "defer"]
funlen:
lines: 80
statements: 60
varnamelen:
# The longest distance, in source lines, that is being considered a "small scope".
# Variables used in at most this many lines will be ignored.
# Default: 5
max-distance: 26
ignore-names:
- err
- id
- ch
- wg
- mu
ignore-decls:
- c echo.Context
- t testing.T
- f *foo.Bar
- e error
- i int
- const C
- T any
- m map[string]int
errcheck:
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: true
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
# default is false: such cases aren't reported by default.
check-blank: true
govet:
# report about shadowed variables
check-shadowing: false
gofmt:
# simplify code: gofmt with `-s` option, true by default
simplify: true
gocyclo:
# minimal code complexity to report, 30 by default (but we recommend 10-20)
min-complexity: 15
maligned:
# print struct with more effective memory layout or not, false by default
suggest-new: true
dupl:
# tokens count to trigger issue, 150 by default
threshold: 100
goconst:
# minimal length of string constant, 3 by default
min-len: 3
# minimal occurrences count to trigger, 3 by default
min-occurrences: 3
depguard:
list-type: blacklist
# Packages listed here will reported as error if imported
packages:
- github.com/golang/protobuf/proto
misspell:
# Correct spellings using locale preferences for US or UK.
# Default is to use a neutral variety of English.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
locale: US
lll:
# max line length, lines longer will be reported. Default is 120.
# '\t' is counted as 1 character by default, and can be changed with the tab-width option
line-length: 120
# tab width in spaces. Default to 1.
tab-width: 1
unused:
# treat code as a program (not a library) and report unused exported identifiers; default is false.
# XXX: if you enable this setting, unused will report a lot of false-positives in text editors:
# if it's called for subdir of a project it can't find funcs usages. All text editor integrations
# with golangci-lint call it on a directory with the changed file.
check-exported: false
unparam:
# call graph construction algorithm (cha, rta). In general, use cha for libraries,
# and rta for programs with main packages. Default is cha.
algo: cha
# Inspect exported functions, default is false. Set to true if no external program/library imports your code.
# XXX: if you enable this setting, unparam will report a lot of false-positives in text editors:
# if it's called for subdir of a project it can't find external interfaces. All text editor integrations
# with golangci-lint call it on a directory with the changed file.
check-exported: false
nakedret:
# make an issue if func has more lines of code than this setting and it has naked returns; default is 30
max-func-lines: 60
nolintlint:
allow-unused: false
allow-leading-space: false
allow-no-explanation: []
require-explanation: false
require-specific: true
prealloc:
# XXX: we don't recommend using this linter before doing performance profiling.
# For most programs usage of prealloc will be a premature optimization.
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# True by default.
simple: true
range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: false # Report preallocation suggestions on for loops, false by default
cyclop:
# the maximal code complexity to report
max-complexity: 20
gomoddirectives:
replace-local: true
retract-allow-no-explanation: false
exclude-forbidden: true
linters:
enable-all: true
disable-all: false
fast: false
disable:
- golint
- varcheck
- ifshort
- structcheck
- deadcode
# - nosnakecase
- interfacer
- maligned
- scopelint
- exhaustivestruct
- testpackage
- promlinter
- nonamedreturns
- makezero
- gofumpt
- nlreturn
- thelper
# Start from the standard set (errcheck, govet, ineffassign, staticcheck,
# unused) and add a few low-noise, high-value linters on top.
default: standard
enable:
- bodyclose
- misspell
- unconvert
- usestdlibvars
settings:
errcheck:
exclude-functions:
- (*encoding/json.Encoder).Encode
- (net/http.ResponseWriter).Write
- fmt.Fprintf
- fmt.Fprint
- fmt.Fprintln
misspell:
locale: US
staticcheck:
checks:
- all
# Deprecations are tracked separately; some (e.g. gRPC dial options)
# are kept intentionally for compatibility. Migrate them on their own.
- -SA1019
# Initialism/naming convention (Id->ID, Http->HTTP, ...). The remaining
# offenders are exported identifiers (e.g. web.Id, web.DefaultId) whose
# rename is a breaking API change; not worth it in a lint-bootstrap pass.
- -ST1003
exclusions:
# Use golangci-lint's built-in sensible exclusions and skip generated code.
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
# The protobuf code generator is a port of upstream protoc-gen-go and
# keeps its structure; don't flag its unused legacy helpers.
- path: cmd/protoc-gen-micro/generator/
linters:
- unused
# Tests are held to a looser standard.
- path: _test\.go
linters:
- bodyclose
- errcheck
# Demo/harness code: fire-and-forget calls are fine and `_ =` noise hurts
# readability of examples.
- path: (^|/)(examples|internal/harness)/
linters:
- errcheck
# Can be considered to be enabled
- gochecknoinits
- gochecknoglobals # RIP
- dogsled
- wrapcheck
- paralleltest
- ireturn
- gomnd
- goerr113
- exhaustruct
- containedctx
- godox
- forcetypeassert
- gci
- lll
issues:
# List of regexps of issue texts to exclude, empty list by default.
# But independently from this option we use default exclude patterns,
# it can be disabled by `exclude-use-default: false`. To list all
# excluded by default patterns execute `golangci-lint run --help`
# exclude:
# - package comment should be of the form "Package services ..." # revive
# - ^ST1000 # ST1000: at least one file in a package should have a package comment (stylecheck)
# exclude-rules:
# - path: internal/app/machined/pkg/system/services
# linters:
# - dupl
exclude-rules:
- path: _test\.go
linters:
- gocyclo
- dupl
- gosec
- funlen
- varnamelen
- wsl
# Independently from option `exclude` we use default exclude patterns,
# it can be disabled by this option. To list all
# excluded by default patterns execute `golangci-lint run --help`.
# Default value for this option is true.
exclude-use-default: false
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-issues-per-linter: 0
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
max-same-issues: 0
# Show only new issues: if there are unstaged changes or untracked files,
# only those changes are analyzed, else only changes in HEAD~ are analyzed.
# It's a super-useful option for integration of golangci-lint into existing
# large codebase. It's not practical to fix all existing issues at the moment
# of integration: much better don't allow issues in new code.
# Default is false.
new: false
formatters:
enable:
- gofmt
+136
View File
@@ -0,0 +1,136 @@
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj
version: 2
before:
hooks:
- go mod tidy
builds:
- main: ./cmd/micro
id: micro
binary: micro
env:
- CGO_ENABLED=0
- >-
{{- if eq .Os "darwin" }}
{{- if eq .Arch "amd64"}}CC=o64-clang{{- end }}
{{- if eq .Arch "arm64"}}CC=aarch64-apple-darwin20.2-clang{{- end }}
{{- end }}
{{- if eq .Os "windows" }}
{{- if eq .Arch "amd64" }}CC=x86_64-w64-mingw32-gcc{{- end }}
{{- end }}
goos:
- linux
- windows
- darwin
goarch:
- amd64
- arm
- arm64
goarm:
- 7
ignore:
- goos: windows
goarch: arm
- main: ./cmd/protoc-gen-micro
id: protoc-gen-micro
binary: protoc-gen-micro
env:
- CGO_ENABLED=0
- >-
{{- if eq .Os "darwin" }}
{{- if eq .Arch "amd64"}}CC=o64-clang{{- end }}
{{- if eq .Arch "arm64"}}CC=aarch64-apple-darwin20.2-clang{{- end }}
{{- end }}
{{- if eq .Os "windows" }}
{{- if eq .Arch "amd64" }}CC=x86_64-w64-mingw32-gcc{{- end }}
{{- end }}
goos:
- linux
- windows
- darwin
goarch:
- amd64
- arm
- arm64
goarm:
- 7
ignore:
- goos: windows
goarch: arm
archives:
- id: micro
ids:
- micro
formats: [tar.gz]
name_template: >-
{{ .Binary }}_
{{- .Os }}_
{{- .Arch }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
files:
- none*
format_overrides:
- goos: windows
formats: [zip]
- id: protoc-gen-micro
ids:
- protoc-gen-micro
formats: [tar.gz]
name_template: >-
{{ .Binary }}_
{{- .Os }}_
{{- .Arch }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
files:
- none*
format_overrides:
- goos: windows
formats: [zip]
report_sizes: true
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
dockers_v2:
-
ids:
- micro
- protoc-gen-micro
images:
- "micro/micro"
- "ghcr.io/micro/go-micro"
tags:
- "v{{ .Version }}"
- "{{ if .IsNightly }}nightly{{ end }}"
- "{{ if not .IsNightly }}latest{{ end }}"
labels:
"io.artifacthub.package.readme-url": "https://raw.githubusercontent.com/micro/go-micro/refs/heads/master/README.md"
"io.artifacthub.package.logo-url": "https://www.gravatar.com/avatar/09d1da3ea9ee61753219a19016d6a672?s=120&r=g&d=404"
"org.opencontainers.image.description": "A Go Platform built for Developers"
"org.opencontainers.image.created": "{{.Date}}"
"org.opencontainers.image.title": "{{.ProjectName}}"
"org.opencontainers.image.revision": "{{.FullCommit}}"
"org.opencontainers.image.version": "{{.Version}}"
"org.opencontainers.image.source": "{{.GitURL}}"
"org.opencontainers.image.url": "{{.GitURL}}"
"org.opencontainers.image.licenses": "MIT"
platforms:
- linux/amd64
- linux/arm64
retry:
attempts: 5
delay: 5s
max_delay: 2m
-29
View File
@@ -1,29 +0,0 @@
labelType: long
coverThreshold: 70
buildStyle:
bold: true
foreground: yellow
startStyle:
foreground: lightBlack
passStyle:
foreground: green
failStyle:
bold: true
foreground: "#821515"
skipStyle:
foreground: lightBlack
passPackageStyle:
foreground: green
hide: false
failPackageStyle:
bold: true
foreground: "#821515"
coveredStyle:
foreground: green
uncoveredStyle:
bold: true
foreground: yellow
fileStyle:
foreground: cyan
lineStyle:
foreground: magenta
+137
View File
@@ -0,0 +1,137 @@
{
"folders": [
{
"path": "."
}
],
"settings": {
"go.toolsManagement.autoUpdate": true,
"go.useLanguageServer": true,
"go.lintOnSave": "workspace",
"go.lintTool": "golangci-lint",
"go.lintFlags": [
"--fast"
],
"go.formatTool": "goimports",
"go.formatFlags": [],
"go.buildOnSave": "workspace",
"go.testOnSave": false,
"go.coverOnSave": false,
"go.testFlags": ["-v", "-race"],
"go.testTimeout": "60s",
"go.gopath": "",
"go.goroot": "",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/node_modules": true,
"**/*.test": true,
"**/coverage.out": true,
"**/coverage.html": true
},
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/**": true,
"**/.vscode/**": true
},
"search.exclude": {
"**/node_modules": true,
"**/bower_components": true,
"**/*.code-search": true,
"**/vendor": true,
"**/.git": true
},
"[go]": {
"editor.tabSize": 4,
"editor.insertSpaces": false,
"editor.formatOnSave": true,
"editor.defaultFormatter": "golang.go"
},
"[go.mod]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "golang.go"
},
"[markdown]": {
"editor.formatOnSave": false,
"editor.wordWrap": "on"
},
"gopls": {
"ui.semanticTokens": true,
"ui.completion.usePlaceholders": true,
"formatting.gofumpt": false,
"analyses": {
"unusedparams": true,
"shadow": true,
"fieldalignment": false
}
}
},
"extensions": {
"recommendations": [
"golang.go",
"editorconfig.editorconfig",
"redhat.vscode-yaml",
"ms-vscode.makefile-tools"
]
},
"tasks": {
"version": "2.0.0",
"tasks": [
{
"label": "Run Tests",
"type": "shell",
"command": "make test",
"group": {
"kind": "test",
"isDefault": true
},
"presentation": {
"reveal": "always",
"panel": "new"
}
},
{
"label": "Run Tests with Coverage",
"type": "shell",
"command": "make test-coverage",
"group": "test"
},
{
"label": "Run Linter",
"type": "shell",
"command": "make lint",
"group": "build"
},
{
"label": "Format Code",
"type": "shell",
"command": "make fmt",
"group": "build"
}
]
},
"launch": {
"version": "0.2.0",
"configurations": [
{
"name": "Debug Current File",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${file}"
},
{
"name": "Debug Test",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}"
}
]
}
}
+15
View File
@@ -0,0 +1,15 @@
# Repository agent instructions
These instructions apply to the entire repository.
## Pull requests from Codex tasks
When a Codex task makes repository changes and the requested outcome is a PR:
1. Keep the change focused on the assigned issue or prompt.
2. Run the relevant verification commands and capture their results.
3. Check `git status --short` and review the diff before finishing.
4. Stage the intended files and create a local git commit on the current branch.
5. Use the Codex `make_pr` tool to open the pull request with a concise title and a body that summarizes the change and testing.
Do not just say that a PR was opened. If local changes exist, the task is not complete until the changes are committed and the `make_pr` tool has been called. A GitHub token in the shell environment is not a substitute for the Codex `make_pr` tool in this environment.
+126
View File
@@ -0,0 +1,126 @@
# Changelog
All notable changes to Go Micro are documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/). Go Micro uses
calendar-based versions (YYYY.MM) for the AI-native era.
---
## [6.0.0] - June 2026
The AI-native major release. Breaking changes are listed first; everything
else is additive. See the [v5 → v6 migration guide](internal/website/docs/guides/migration/v5-to-v6.md) — it's a small upgrade.
### Changed (breaking)
- **Module path is now `go-micro.dev/v6`.** Update imports (`go-micro.dev/v5/...``go-micro.dev/v6/...`) and `go install go-micro.dev/v6/cmd/micro@v6`.
- **TLS verification is on by default.** v5 skipped verification unless `MICRO_TLS_SECURE=true`; v6 verifies by default. `MICRO_TLS_SECURE` is removed — set `MICRO_TLS_INSECURE=true` (or call `tls.InsecureConfig()`) for self-signed/dev certs.
- **`micro.NewService(name, opts...)` is the service constructor**, symmetric with `NewAgent`/`NewFlow`. `micro.New(name, opts...)` remains as a deprecated alias; the old name-less `micro.NewService(opts...)` form is removed (pass the name positionally). Generators emit the new form.
- **JWT auth ported in-module.** The external `github.com/micro/plugins/v5/auth/jwt` (pinned to v5) is replaced by `go-micro.dev/v6/auth/jwt/token`, now on the maintained `golang-jwt/jwt/v5`; the deprecated `dgrijalva/jwt-go` dependency is dropped.
### Added
- **A2A protocol — both directions** — `gateway/a2a` exposes registered agents over the open Agent2Agent (A2A) protocol so agents on other frameworks can discover and call them: Agent Cards are generated from registry metadata (the same way the MCP gateway derives tools), and incoming tasks are translated to the agent's existing `Agent.Chat` RPC, with no per-agent code (`micro a2a serve`). The outbound `a2a.Client` calls external A2A agents by URL, wired into `flow.A2A(url)` (a workflow step) and `delegate` to an `http(s)` URL (from inside an agent). An agent can also serve A2A **directly** without a gateway via `AgentA2A(addr)` (`a2a.NewAgentHandler`), handling tasks in-process. v1 is the synchronous JSON-RPC binding (`message/send`, `tasks/get`, card discovery); streaming and push notifications are advertised as unsupported. (`gateway/a2a/`, `cmd/micro/a2a/`)
- **Agents (`micro.NewAgent`)** — an agent is a service with an LLM inside: it discovers its assigned services as tools, runs the model's tool loop, registers a `Chat` RPC endpoint, and is reachable like any service. `Ask` for programmatic use; `micro chat` discovers and routes to agents; `micro agent list`/`describe`. (`agent/`)
- **Plan & delegate** — two built-in agent tools added to every agent: `plan` (an ordered, store-persisted plan surfaced back in the prompt) and `delegate` (hand a self-contained subtask to a registered agent over RPC, otherwise to an ephemeral sub-agent). No harness or graph — they're plain tools. (`agent/builtin.go`, `examples/agent-plan-delegate/`)
- **Agent guardrails** — `MaxSteps` (stop on count), `LoopLimit` (stop repeated no-progress calls; on by default), and `ApproveTool` (human-in-the-loop / policy gate before each action), enforced at the one point every tool call passes through. (`agent/`, guide + blog)
- **Pluggable agent memory & custom tools** — durable store-backed conversation memory by default, swappable via `AgentMemory`; register any function as a tool with `AgentTool`.
- **Workflows (`micro.NewFlow`)** — event-driven orchestration that maps to Anthropic's workflow/agent split: an event triggers a deterministic step (or ordered durable steps), or dispatches to an agent with `FlowAgent`. (`flow/`)
- **Flow loops (`FlowLoop`)** — a flow step that runs a body step repeatedly, carrying state across passes, until a stop condition is met or a hard iteration cap is hit. Stop on a code-defined predicate (`FlowUntil`) or let the model judge it done (`FlowUntilLLM` — the supervised "Ralph" loop); `FlowLoopMax` is the guardrail that guarantees termination, and `FlowOnIteration` reports progress. (`flow/loop.go`, `examples/flow-loop/`, guide)
- **x402 payments** — opt-in per-call payments for tools via the x402 standard, with a pluggable facilitator and a consumer-side client + budget; the MCP gateway can advertise and require payment per tool. (`wrapper/x402/`, guide + blog)
- **Scoped store state** — `store.Scope(s, database, table)` returns a store handle that confines every operation to a database/table without mutating the shared store (unlike `Init(Table(...))`, which is process-global and races between co-located components). Services, agents, and flows now each keep their state in their own table (`service/{name}`, `agent/{name}`, `flow/{name}`); the service path replaces the old `Init(store.Table(name))` global mutation with a scoped handle.
- **Flow discovery & history CLI** — running flows now register in the registry as `type=flow` (and deregister on `Stop`), so they're discoverable like agents: `micro flow list` shows running flows, `micro flow runs <name>` shows a flow's durable run history from the store, and `micro agent history <name>` shows an agent's stored conversation. Live state comes from the registry; durable history from the scoped store.
- **Durable workflows** — a flow can now be an ordered list of steps (a task with stages) that is checkpointed before and after each step, so a run survives a crash and resumes where it stopped without re-running completed steps. State carries a typed payload plus a `Stage` marker; flow-level `Retry` with a per-step override; runs retained for audit unless `DeleteOnSuccess`. Step actions: `Call` (RPC), `LLM` (model turn), `Dispatch` (to an agent), or any `StepFunc`. Durability is a pluggable `Checkpoint` (store-backed by default; implement the interface for Temporal/Restate). Runnable example: `examples/flow-durable/`. Blog: "Durable Workflows" (`internal/website/blog/24.md`).
- **Agent tool-execution wrappers** — `AgentWrapTool` registers middleware around an agent's tool calls, the tool-side analogue of `client.CallWrapper`/`server.HandlerWrapper`. Use it for logging, metrics, retries, or policy; wrappers compose outermost-first and run outside the built-in guardrails. Includes a runnable example with observe + retry wrappers (`examples/agent-wrap-tool/`).
- **Agent platform showcase** — full platform example (Users, Posts, Comments, Mail) mirroring [micro/blog](https://github.com/micro/blog), demonstrating how existing microservices become agent-accessible with zero code changes (`examples/mcp/platform/`).
- **Blog post: "Your Microservices Are Already an AI Platform"** — walkthrough of agent-service interaction patterns using real-world services (`internal/website/blog/7.md`).
- **Circuit breakers for MCP gateway** — per-tool circuit breakers protect downstream services from cascading failures. Configurable max failures, open-state timeout, and half-open probing. Available via `Options.CircuitBreaker` and `--circuit-breaker` CLI flag (`gateway/mcp/circuitbreaker.go`).
- **Helm chart for MCP gateway** — official Helm chart at `deploy/helm/mcp-gateway/` with Deployment, Service, ServiceAccount, HPA, and Ingress templates. Supports Consul/etcd/mDNS registries, JWT auth, rate limiting, audit logging, per-tool scopes, TLS ingress, and auto-scaling.
- **MCP gateway benchmarks** — comprehensive benchmark suite for tool listing, lookup, auth, rate limiting, and JSON serialization (`gateway/mcp/benchmark_test.go`)
- **Workflow example** — cross-service orchestration demo with Inventory, Orders, and Notifications services showing agents chaining multi-step workflows from natural language (`examples/mcp/workflow/`)
- **Docker Compose deployment** — production-like setup with Consul registry, standalone MCP gateway, and Jaeger tracing in one `docker-compose up` (`examples/deployment/`)
---
## [2026.03] - March 2026
### Added
#### Developer Experience
- **`micro new` MCP templates** — `micro new myservice` generates MCP-enabled services with doc comments, `@example` tags, and `WithMCP()` wired in. Use `--no-mcp` to opt out.
- **`micro.NewService("name")` unified API** — single way to create services: `micro.NewService("greeter")` or `micro.NewService("greeter", micro.Address(":8080"))`. Replaces `micro.NewService()` + `service.New()` dual API.
- **`service.Handle()` simplified registration** — register handlers with `service.Handle(new(Greeter))` instead of manual `server.NewHandler` + `server.Handle`.
- **`micro.NewGroup()` modular monoliths** — run multiple services in one binary with shared lifecycle: `micro.NewGroup(users, orders).Run()`.
- **`mcp.WithMCP()` one-liner** — add MCP to any service with a single option: `micro.NewService("name", mcp.WithMCP(":3001"))`.
- **CRUD example** — contact book service with 6 operations, rich agent docs, and validation patterns (`examples/mcp/crud/`).
#### MCP Gateway
- **WebSocket transport** — bidirectional JSON-RPC 2.0 streaming over WebSocket for real-time agent communication (`gateway/mcp/websocket.go`).
- **OpenTelemetry integration** — full span instrumentation across HTTP, stdio, and WebSocket transports with W3C trace context propagation (`gateway/mcp/otel.go`).
- **Standalone gateway binary** — `micro-mcp-gateway` with Docker support for running the MCP gateway independently of services.
- **Per-tool auth scopes** — service-level (`server.WithEndpointScopes()`) and gateway-level (`Options.Scopes`) scope enforcement with bearer token auth.
- **Rate limiting** — per-tool token bucket rate limiting (`Options.RateLimit`).
- **Audit logging** — immutable audit records per tool call with trace ID, account, scopes, duration, and errors (`Options.AuditFunc`).
#### AI Model Package
- **`model.Model` interface** — unified AI provider abstraction with `Generate()` and `Stream()` methods.
- **Anthropic Claude provider** — `model/anthropic` with tool execution and auto-calling.
- **OpenAI GPT provider** — `model/openai` with provider auto-detection from base URL.
#### Agent SDKs
- **LangChain SDK** — `contrib/langchain-go-micro/` Python package with auto-discovery, tool generation, and multi-agent workflow examples.
- **LlamaIndex SDK** — `contrib/go-micro-llamaindex/` Python package with RAG integration examples.
#### Documentation
- **AI-native services guide** — building services for AI agents from scratch
- **MCP security guide** — auth, scopes, and audit logging
- **Tool descriptions guide** — writing doc comments that improve agent performance
- **Agent patterns guide** — architecture patterns for agent integration
- **Error handling guide** — writing agent-friendly error responses with typed errors
- **Troubleshooting guide** — common MCP issues and solutions
- **Migration guide** — add MCP to existing services in 5 minutes
#### CLI
- **`micro mcp serve`** — start MCP server (stdio for Claude Code, HTTP for web agents)
- **`micro mcp list`** — list available tools (human-readable or JSON)
- **`micro mcp test`** — test tools with JSON input
- **`micro mcp docs`** — generate tool documentation
- **`micro mcp export`** — export to LangChain, OpenAPI, or JSON formats
#### Agent Playground
- **Chat-focused UI** — redesigned playground with collapsible tool calls, real-time status, and thinking indicators
- **Provider settings** — configurable OpenAI/Anthropic provider, model, and API key
### Changed
- Service interface moved to `service.Service` with `micro.Service` as a type alias for backward compatibility.
- `service.New()` returns `service.Service` interface (was `*ServiceImpl`).
- `service.NewGroup()` accepts `service.Service` interface (was `*ServiceImpl`).
- `go.mod` template in `micro new` updated to Go 1.22.
### Fixed
- Handler `Handle()` method accepts variadic `server.HandlerOption` for scopes and metadata.
- Store initialization uses service name as table automatically.
- Service `Stop()` properly aggregates errors from lifecycle hooks.
---
## [2026.02] - February 2026
### Added
- **MCP gateway library** — `gateway/mcp/` with HTTP/SSE and stdio transports, service discovery, tool generation, and JSON schema generation from Go types (2,500+ lines).
- **CLI integration** — `micro run --mcp-address` flag to start MCP alongside services.
- **Documentation extraction** — auto-extract tool descriptions from Go doc comments with `@example` tag and struct tag parsing.
- **Blog post** — "Making Microservices AI-Native with MCP"
- **MCP examples** — `examples/mcp/hello/` and `examples/mcp/documented/`
---
## [2026.01] - January 2026
### Added
- **`micro deploy`** — deploy services to any Linux server via SSH + systemd with `micro deploy user@server`.
- **`micro build`** — build Go binaries and Docker images with `micro build --docker`.
- **Blog post** — "Introducing micro deploy"
---
_For earlier changes, see the [git log](https://github.com/micro/go-micro/commits/master)._
+158
View File
@@ -0,0 +1,158 @@
# CLAUDE.md - Go Micro Project Guide
## Project Overview
Go Micro is a framework for distributed systems development in Go. It provides pluggable abstractions for service discovery, RPC, pub/sub, config, auth, storage, and more.
The framework is evolving into an **AI-native platform** where every microservice is automatically accessible to AI agents via the Model Context Protocol (MCP).
## Build & Test
```bash
# Run all tests
make test
# Run tests for a specific package
go test ./gateway/mcp/...
go test ./ai/...
go test ./model/...
# Lint
make lint
# Format
make fmt
# Build CLI
go build -o micro ./cmd/micro
# Run locally with hot reload
micro run
```
## Project Structure
```
go-micro/
├── agent/ # Agent abstraction (intelligent service management)
├── ai/ # AI model providers (Anthropic, OpenAI, Gemini, etc.)
├── auth/ # Authentication (JWT, no-op)
├── broker/ # Message broker (NATS, RabbitMQ)
├── cache/ # Caching (Redis)
├── client/ # RPC client (gRPC)
├── cmd/micro/ # CLI tool (run, deploy, mcp, build, server)
├── codec/ # Message codecs (JSON, Proto)
├── config/ # Dynamic config (env, file, etcd, NATS)
├── errors/ # Error handling
├── events/ # Event system (NATS JetStream)
├── flow/ # Event-driven LLM orchestration
├── gateway/
│ ├── api/ # REST API gateway
│ └── mcp/ # MCP gateway (core AI integration)
│ └── deploy/ # Helm charts for MCP gateway
├── health/ # Health checking
├── logger/ # Logging
├── metadata/ # Context metadata
├── model/ # Typed data models (CRUD, queries, schemas)
├── registry/ # Service discovery (mDNS, Consul, etcd)
├── selector/ # Client-side load balancing
├── server/ # RPC server
├── service/ # Service interface + profiles
├── store/ # Data persistence (Postgres, NATS KV)
├── transport/ # Network transport
├── wrapper/ # Middleware (auth, trace, metrics)
├── examples/ # Working examples
└── internal/ # Non-public: docs, utils, test harness
```
## Key Architectural Decisions
- **Plugin architecture**: All abstractions use Go interfaces. Defaults work out of the box, everything is swappable.
- **Progressive complexity**: Zero-config for development, full control for production.
- **AI-native by default**: Every service is automatically an MCP tool. No extra code needed.
- **In-repo plugins**: Plugins live in the main repo to avoid version compatibility issues.
- **Reflection-based registration**: Handlers are registered via reflection for minimal boilerplate.
## Code Conventions
- Standard Go conventions (gofmt, golint)
- Functional options pattern for configuration (`WithX()` functions)
- Interface-first design: define the interface, then implement
- Tests alongside code (not in separate test directories)
- Commit messages: imperative mood, concise summary line
## Current Focus & Priorities (March 2026)
### Status
- **Q1 2026 (MCP Foundation):** COMPLETE
- **Q2 2026 (Agent DX):** COMPLETE (100%)
- **Q3 2026 (Production):** 50% complete (ahead of schedule)
### Priority 1: Agent Showcase & Examples
Build compelling demos showing agents interacting with go-micro services in realistic scenarios.
### Priority 2: Additional Protocol Support
- gRPC reflection-based MCP
- HTTP/3 support
### Priority 3: Kubernetes & Deployment
- Helm Charts for MCP gateway
- Kubernetes Operator with CRDs
### Recently Completed
- **Agent Plan & Delegate** - Two built-in agent tools: `plan` (ordered plan persisted to store-backed memory, surfaced in the prompt) and `delegate` (hand a subtask to another agent — RPC to a registered agent, else an ephemeral sub-agent with isolated context). Added automatically to every agent; no harness or graph. (`agent/builtin.go`, `examples/agent-plan-delegate/`)
- **`micro new` MCP Templates** - Scaffolds MCP-enabled services with doc comments, `@example` tags, `WithMCP()`. `--no-mcp` to opt out.
- **CRUD Example** - Contact book service with 6 operations, rich agent docs (`examples/mcp/crud/`)
- **Migration Guide** - "Add MCP to Existing Services" guide with 3 approaches
- **Troubleshooting Guide** - Common MCP issues and solutions
- **Error Handling Guide** - Patterns for agent-friendly error responses
- **Documentation Guides** - Six guides: AI-native services, MCP security, tool descriptions, agent patterns, error handling, troubleshooting
- **WithMCP Option** - One-line MCP setup (`gateway/mcp/option.go`)
- **Agent Playground Redesign** - Chat-focused UI with collapsible tool calls
- **Standalone Gateway Binary** - `micro-mcp-gateway` with Docker support
- **WebSocket Transport** - Bidirectional JSON-RPC 2.0 streaming (`gateway/mcp/websocket.go`)
- **OpenTelemetry Integration** - Full span instrumentation with W3C trace context (`gateway/mcp/otel.go`)
- **LlamaIndex SDK** - Python package with RAG examples (`contrib/go-micro-llamaindex/`)
## Key Files
| Purpose | File |
|---------|------|
| MCP Gateway | `gateway/mcp/mcp.go` |
| MCP Docs | `gateway/mcp/DOCUMENTATION.md` |
| AI Interface | `ai/model.go` |
| Model Layer | `model/model.go` |
| CLI Entry | `cmd/micro/main.go` |
| MCP CLI | `cmd/micro/mcp/` |
| Server (run/server) | `cmd/micro/server/server.go` |
| Roadmap | `ROADMAP.md` (full: `internal/website/docs/roadmap.md`) |
| Status | `CHANGELOG.md` |
| Changelog | `CHANGELOG.md` |
| Docs Site | `internal/website/docs/` |
## Roadmap & Status Documents
- **[ROADMAP.md](ROADMAP.md)** - the single, current roadmap (agentic development + DX). Full version at `internal/website/docs/roadmap.md`.
- **[CHANGELOG.md](CHANGELOG.md)** - what shipped and when (the source of truth for status).
- **[internal/docs/IMPLEMENTATION_SUMMARY.md](internal/docs/IMPLEMENTATION_SUMMARY.md)** - Implementation notes
- **[CHANGELOG.md](CHANGELOG.md)** - What changed and when
## Coordination with Codex
Go Micro is maintained by two AI tools — **Claude Code** (you) and **Codex** (its playbook is [CODEX.md](CODEX.md)) — plus the human maintainer, who routes work and owns every merge. To work side by side without collisions:
- **Lanes / branches.** You work on `claude/*` branches; Codex on `codex/*`. Never push to Codex's branch, and never have both agents committing the same branch at once.
- **Base PRs on `master`; don't stack on Codex's in-flight branch.** If that base squash-merges, your commit gets orphaned (this happened — the #3007 fixes had to be re-landed). If the code you need isn't merged yet, wait for it, then branch off `master`. To improve an *open* Codex PR, fix it in place (once Codex is done with the branch, or via an `@codex` comment on the PR) rather than a separate stacked PR.
- **One concern per PR.** Single-purpose PRs; don't bundle (e.g.) a feature with a docs change.
- **Cross-review.** Review Codex's PRs before merge — mechanical fixes you can land yourself (based on `master`), but design/scope/positioning calls go to the human; don't silently rewrite Codex's intent. Codex reviews yours via `@codex review`.
- **Dispatching Codex.** Start a task by commenting `@codex <instruction>` on an issue/PR (that issue/PR is its context). `@codex review` is reserved for review; any other instruction starts a *task*. It's consequential (spends a Codex task slot, pushes commits) and **serial** (one task at a time) — so dispatch one task at a time, only on the human's go-ahead, and never write a literal `@codex` in a comment unless you intend to trigger it (write "Codex" in prose otherwise).
- **CI is the gate.** `go build`, `go test`, `golangci-lint` (blocking), and `make harness` must pass before merge. `internal/harness/` and `examples/` are excluded from errcheck; everything else gets the full set.
- **Backlog = GitHub issues**, each a scoped, self-contained brief with acceptance criteria.
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md) for full guidelines. Key points:
- Open an issue before large changes
- Include tests for new features
- Run `make test` and `make lint` before submitting
- Follow commit message format: `type: description` (e.g., `feat: add WebSocket transport`)
+197
View File
@@ -0,0 +1,197 @@
# Codex Maintainer Playbook
Go Micro has six months of Codex access through OpenAI's Codex for Open Source
program. Use it to increase maintainer throughput without changing the project's
bar for review, tests, or design taste.
## Operating principles
1. **Humans set direction; Codex accelerates execution.** Maintainers choose the
issue, constraints, and acceptance criteria. Codex drafts, investigates, and
verifies.
2. **Small, reviewable changes win.** Prefer focused PRs that can be understood
in one sitting over large speculative rewrites.
3. **Keep the contract green.** Every Codex-assisted change should preserve the
CLI-first getting-started flow, the harnesses, `make test`, and `make lint`.
4. **Document while coding.** If behavior changes, ask Codex to update examples,
guides, and release notes in the same branch.
5. **No blind merges.** Codex output is treated like any contributor output:
reviewed by a maintainer, backed by tests, and checked for public API impact.
## Coordination with Claude Code
Go Micro is maintained by two AI tools — **Codex** (you) and **Claude Code** (its guide is [CLAUDE.md](CLAUDE.md)) — plus the human maintainer, who routes work and owns every merge.
- **Lanes / branches.** You work on `codex/*` branches; Claude Code on `claude/*`. Never push to a branch the other owns, and never have both agents on one branch at once.
- **Base PRs on `master`.** Don't stack a PR on another agent's in-flight branch — if that base squash-merges, your changes can be orphaned. If the code you need isn't merged yet, wait, then branch off `master`. To improve a PR that hasn't merged, push to that PR's branch rather than opening a separate stacked PR — keep the change one mergeable unit.
- **One concern per PR.** Keep each PR single-purpose so a reviewer can read it in one sitting; don't bundle unrelated changes (e.g. a feature plus a docs rebrand).
- **Cross-review before merge.** Claude Code reviews your PRs; you review its with `@codex review`. A fresh pass from the other model catches what the author misses.
- **Dispatch.** Maintainers (or Claude Code) start your tasks with `@codex <instruction>` on the relevant issue/PR — that's your context. `@codex review` is review; any other instruction is a *task*. You run one task at a time: take the current one to a clean, green PR before the next is dispatched.
- **CI is the gate.** `go build`, `go test`, `golangci-lint` (blocking), and `make harness` must pass; never merge red. `internal/harness/` and `examples/` are excluded from errcheck; everything else gets the full set.
- **Backlog = GitHub issues**, each a scoped brief with acceptance criteria.
## Best uses
### 1. PR review and triage
- Summarize a PR: changed surface area, public API impact, tests added or missing.
- Ask for targeted review passes: concurrency, cancellation, security, backwards
compatibility, docs drift, and examples.
- Convert review findings into small patch suggestions or issue comments.
### 2. Issue reproduction
- Turn bug reports into failing tests or runnable reproduction scripts.
- Minimize flakes by isolating registry, broker, store, transport, and AI-provider
dependencies behind deterministic fakes where possible.
- Attach the exact command that reproduces the failure to the issue.
### 3. Release support
- Draft changelog entries from merged commits, grouped by feature, fix, docs, and
compatibility notes.
- Check that `README.md`, `ROADMAP.md`, website docs, examples, and `CHANGELOG.md`
agree before tagging.
- Run dry-run release commands and summarize blockers.
### 4. Docs and examples
- Keep the 0→1 path current: scaffold, run, call, chat, inspect.
- Keep the 0→hero example current: a realistic multi-agent system that exercises
agents, services, flows, MCP, A2A, and observability.
- Add runnable examples for new primitives before adding broad prose.
### 5. Hardening backlog
Use Codex to break roadmap items into small PRs, especially:
- cross-provider conformance scenarios for all supported AI providers;
- timeout, cancellation, retry, and rate-limit behavior;
- durable agent loops on top of the existing checkpoint model;
- streaming across `ai.Stream` and A2A;
- agent run metadata mapped to OpenTelemetry spans.
## Suggested weekly loop
1. Pick one maintenance lane: reviews, bugs, release prep, docs, or hardening.
2. Ask Codex for a branch-sized plan with acceptance criteria and test commands.
3. Have Codex implement the smallest valuable slice.
4. Run the relevant checks locally and in CI.
5. Review the diff as maintainer-owned code, then merge or send it back.
6. Record any recurring prompt, check, or failure mode in this playbook.
## First two weeks
Do not start with a giant feature. Start by making Codex pay rent on maintenance
work that is already on the roadmap and easy to review.
### Day 1: set up the review loop
1. Pick three recent PRs or commits: one feature, one bug fix, and one docs-only
change.
2. Ask Codex to review each using the PR review template below.
3. Compare Codex findings with maintainer judgment. Keep the checks that found
real issues; delete the noisy ones.
4. Turn the final review prompt into a saved project note or issue comment
template.
Success means Codex can produce a useful first-pass review in under ten minutes
without blocking a maintainer on false positives.
### Days 2-3: make bugs reproducible
1. Pick one open bug or flaky area.
2. Ask Codex for a failing test only. Do not allow a fix in the first pass.
3. Review the test for whether it captures the real contract.
4. In a second branch, ask Codex to fix the failure with the smallest patch.
Success means every accepted bug fix starts with a regression test or deterministic
harness case.
### Days 4-5: audit the getting-started contract
Run through the 0→1 path from a clean checkout and ask Codex to patch only the
first broken or confusing step. The target is not new prose; it is a runnable
path that works exactly as documented.
Candidate checks:
```sh
make test
make harness
make lint
go run ./examples/hello-world
go run ./internal/harness/universe
```
### Week 2: choose one roadmap slice
Pick one hardening item and break it into PRs that each land independently. The
best first slice is usually test infrastructure, not product code.
Recommended order:
1. **Provider conformance skeleton**: define one deterministic agent scenario and
gate real-provider runs on credentials.
2. **Cancellation audit**: trace `context.Context` propagation through one package
at a time.
3. **Docs drift audit**: compare `README.md`, `ROADMAP.md`, website docs, and
examples for one shipped feature.
4. **Release checklist dry run**: have Codex build a release-blocker list from the
diff since the previous tag.
## Standing task queue
Keep Codex busy on tasks with clear acceptance criteria:
| Priority | Task | Acceptance criteria |
| --- | --- | --- |
| P0 | PR first-pass review | Summary, risks, required changes, and exact verification commands. |
| P0 | Bug reproduction | A failing test or harness case committed before the fix. |
| P0 | 0→1 docs check | Fresh-checkout commands work as written or a patch fixes the first break. |
| P1 | Cross-provider conformance | One scenario runs against fakes by default and real providers when keys exist. |
| P1 | Cancellation hardening | Tests prove timeout/cancel behavior for the touched package. |
| P1 | Release audit | Changelog, docs, examples, and migration notes agree before tagging. |
| P2 | Example polish | Example is runnable, linked from docs, and covered by a lightweight check. |
## What not to use Codex for yet
- Broad rewrites without a failing test, benchmark, or public design note.
- Public API changes before a maintainer writes the compatibility story.
- Large generated docs that nobody has run.
- Provider-specific behavior that is not checked against the shared `ai.Model`
contract.
## Prompt templates
### PR review
```text
Review this PR for Go Micro. Focus on public API compatibility, cancellation and
context propagation, concurrency safety, tests, and docs drift. Return: summary,
risks, required changes, optional improvements, and exact commands to verify.
```
### Bug reproduction
```text
Reproduce this issue in the smallest Go test or harness change possible. Do not
fix it yet. Explain the failing path and provide the exact command that fails.
```
### Branch implementation
```text
Implement the smallest branch that satisfies this issue. Keep the API compatible
unless explicitly required, update docs/examples when behavior changes, and run
`make test`, `make harness`, and `make lint` or explain any environment blocker.
```
### Release audit
```text
Audit this release branch. Compare CHANGELOG, README, ROADMAP, website docs, and
examples against the diff since the last tag. List inconsistencies, missing
migration notes, and checks to run before tagging.
```
+17 -5
View File
@@ -19,16 +19,24 @@ Be respectful, inclusive, and collaborative. We're all here to build great softw
# Install dependencies
go mod download
# Install development tools
make install-tools
# Run tests
go test ./...
make test
# Run tests with coverage
go test -race -coverprofile=coverage.out ./...
# Run tests with race detector and coverage
make test-coverage
# Run linter (install golangci-lint first)
golangci-lint run
# Run linter
make lint
# Format code
make fmt
```
See `make help` for all available commands.
## Making Changes
### Code Guidelines
@@ -83,6 +91,10 @@ go test -v ./...
# Run specific test
go test -run TestMyFunction ./pkg/...
# Optional: Use richgo for colored output
go install github.com/kyoh86/richgo@latest
richgo test -v ./...
```
### Documentation
+26
View File
@@ -0,0 +1,26 @@
FROM alpine:latest
ARG TARGETPLATFORM
ENV USER=micro
ENV GROUPNAME=$USER
ARG UID=1001
ARG GID=1001
RUN addgroup --gid "$GID" "$GROUPNAME" \
&& adduser \
--disabled-password \
--gecos "" \
--home "/micro" \
--ingroup "$GROUPNAME" \
--no-create-home \
--uid "$UID" "$USER"
ENV PATH=/usr/local/go/bin:$PATH
RUN apk --no-cache add git make curl
COPY --from=golang:1.26.0-alpine /usr/local/go /usr/local/go
COPY $TARGETPLATFORM/micro /usr/local/go/bin/
COPY $TARGETPLATFORM/protoc-gen-micro /usr/local/go/bin/
WORKDIR /micro
EXPOSE 8080
ENTRYPOINT ["/usr/local/go/bin/micro"]
CMD ["server"]
+96
View File
@@ -0,0 +1,96 @@
NAME = micro
GIT_COMMIT = $(shell git rev-parse --short HEAD)
GIT_TAG = $(shell git describe --abbrev=0 --tags --always --match "v*")
GIT_IMPORT = go-micro.dev/v5/cmd/micro
BUILD_DATE = $(shell date +%s)
LDFLAGS = -X $(GIT_IMPORT).BuildDate=$(BUILD_DATE) -X $(GIT_IMPORT).GitCommit=$(GIT_COMMIT) -X $(GIT_IMPORT).GitTag=$(GIT_TAG)
# GORELEASER_DOCKER_IMAGE = ghcr.io/goreleaser/goreleaser-cross:v1.25.7
GORELEASER_DOCKER_IMAGE = ghcr.io/goreleaser/goreleaser:latest
.PHONY: test test-race test-coverage harness provider-conformance lint fmt install-tools proto clean help gorelease-dry-run gorelease-dry-run-docker
# Default target
help:
@echo "Go Micro Development Tasks"
@echo ""
@echo " make test - Run tests"
@echo " make test-race - Run tests with race detector"
@echo " make test-coverage - Run tests with coverage"
@echo " make lint - Run linter"
@echo " make harness - Run deterministic end-to-end harnesses"
@echo " make provider-conformance - Run harnesses against configured live providers"
@echo " make fmt - Format code"
@echo " make install-tools - Install development tools"
@echo " make proto - Generate protobuf code"
@echo " make clean - Clean build artifacts"
$(NAME):
CGO_ENABLED=0 go build -ldflags "-s -w ${LDFLAGS}" -o $(NAME) cmd/micro/main.go
# Run tests
test:
go test -v ./...
# Run tests with race detector
test-race:
go test -v -race ./...
# Run tests with coverage
test-coverage:
go test -v -race -coverprofile=coverage.out -covermode=atomic ./...
go tool cover -html=coverage.out -o coverage.html
@echo "Coverage report: coverage.html"
# Run the end-to-end harnesses (deterministic, mock LLM — no API key).
# The universe harness exits non-zero on assertion failure.
harness:
go run ./internal/harness/universe
go run ./internal/harness/agent-flow
go run ./internal/harness/plan-delegate
# Run the same harnesses against every configured live provider. Providers
# without API keys are skipped; configured providers must pass.
provider-conformance:
go run ./internal/harness/provider-conformance
# Run linter
lint:
golangci-lint run
# Format code
fmt:
gofmt -s -w .
goimports -w .
# Install development tools
install-tools:
@echo "Installing development tools..."
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
go install golang.org/x/tools/cmd/goimports@latest
go install github.com/kyoh86/richgo@latest
go install go-micro.dev/v5/cmd/protoc-gen-micro@latest
@echo "Tools installed successfully"
# Generate protobuf code
proto:
@echo "Generating protobuf code..."
find . -name "*.proto" -not -path "./vendor/*" -exec protoc --proto_path=. --micro_out=. --go_out=. {} \;
# Clean build artifacts
clean:
rm -f coverage.out coverage.html
find . -name "*.test" -type f -delete
go clean -cache -testcache
# Try binary release
gorelease-dry-run:
docker run \
--rm \
-e CGO_ENABLED=0 \
-v $(CURDIR):/$(NAME) \
-v /var/run/docker.sock:/var/run/docker.sock \
-w /$(NAME) \
$(GORELEASER_DOCKER_IMAGE) \
--clean --verbose --skip=publish,validate --snapshot
+351 -125
View File
@@ -1,200 +1,426 @@
# Go Micro [![Go.Dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/go-micro.dev/v5?tab=doc) [![Go Report Card](https://goreportcard.com/badge/github.com/go-micro/go-micro)](https://goreportcard.com/report/github.com/go-micro/go-micro)
# Go Micro [![Go.Dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/go-micro.dev/v6?tab=doc) [![Go Report Card](https://goreportcard.com/badge/github.com/go-micro/go-micro)](https://goreportcard.com/report/github.com/go-micro/go-micro)
Go Micro is a framework for distributed systems development.
Go Micro is an **agent harness** and service framework for Go.
**[📖 Documentation](https://go-micro.dev/docs/)** | [Sponsor the project](https://github.com/sponsors/micro)
A harness is the runtime around an agent: the tools it can call, the memory it keeps, the guardrails that bound it, the workflows that trigger it, the services it depends on, and the protocols other agents use to reach it. Go Micro gives you that harness as Go code. Build an agent and it gets a model, memory, tools, planning, delegation, guardrails, and service discovery; it is reachable over [MCP](https://modelcontextprotocol.io/) and [A2A](https://a2a-protocol.org). Write services and every endpoint becomes an AI-callable tool. Orchestrate the deterministic parts with durable flows. Agents, services, and flows share one runtime because an agent is a distributed system, and building one is building a service.
## Overview
## Sponsors
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.
<a href="https://go-micro.dev/blog/3"><img src="https://upload.wikimedia.org/wikipedia/commons/7/78/Anthropic_logo.svg" height="26" /></a>
&nbsp;&nbsp;
<a href="https://go-micro.dev/blog/29"><img src="https://upload.wikimedia.org/wikipedia/commons/4/4d/OpenAI_Logo.svg" height="26" /></a>
&nbsp;&nbsp;
<a href="https://go-micro.dev/blog/8"><img src="https://www.atlascloud.ai/logo.svg" height="26" /></a>
## Features
**Want to support Go Micro and see your logo here?** [Become a sponsor](https://discord.gg/WeMU5AGxD) — reach out on Discord.
Go Micro abstracts away the details of distributed systems. Here are the main features.
## Commercial Support
- **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.
Running Go Micro in production, or building on it and want help? Paid **support, consulting, training, and retainers** are available directly from the maintainer — and they're what keep the project maintained. See [**Support**](SUPPORT.md) for the tiers, or [open a request](https://github.com/micro/go-micro/issues/new?template=commercial_support.md).
- **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.
## Contents
- **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.
- [Quick Start](#quick-start)
- [Why an Agent Harness](#why-an-agent-harness)
- [Writing Services](#writing-services)
- [Building Agents](#building-agents) — [Plan & Delegate](#plan--delegate), [Pluggable](#batteries-included-pluggable), [Paid tools (x402)](#paid-tools-x402), [A2A](#reachable-by-other-agents-a2a)
- [Features](#features)
- [CLI](#cli)
- [Multi-Service Projects](#multi-service-projects)
- [Data Model](#data-model)
- [AI Providers](#ai-providers)
- [Examples](#examples)
- [Commercial Support](#commercial-support)
- [Docs](#docs)
- **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.
## Quick Start
- **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.
- **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
Install the CLI:
```bash
go get go-micro.dev/v5@latest
# Binary (no Go required)
curl -fsSL https://go-micro.dev/install.sh | sh
# Or with Go
go install go-micro.dev/v6/cmd/micro@v6
```
Create a service and register a handler
### Fastest start — no API key
Scaffold a service, run it, call it:
```bash
micro new helloworld
cd helloworld
micro run
```
Then in another terminal:
```bash
curl -X POST http://localhost:8080/api/helloworld/Helloworld.Call \
-H 'Content-Type: application/json' -d '{"name":"World"}'
```
### Generate from a prompt — with an LLM key
Set a provider key, describe what you want, and the AI designs services, writes handlers, compiles, and starts them:
```bash
export ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY, GEMINI_API_KEY, ...
micro run --prompt "a task management system with categories" --provider anthropic
```
The AI designs the architecture, you review it, then it generates handlers with real business logic, compiles them, and starts them:
```
Services:
● task — Task management with status tracking
● project — Project organization
Generate? [Y/n]
Micro
Services:
● task
● project
Agents:
◆ agent
```
Then talk to your services from the console:
```
> Create a project called Launch, then add three tasks to it
→ project_Project_Create({"name":"Launch"})
← {"record":{"id":"p1..."},"success":true}
→ task_Task_Create({"title":"Design specs","project_id":"p1..."})
→ task_Task_Create({"title":"Write code","project_id":"p1..."})
→ task_Task_Create({"title":"Ship it","project_id":"p1..."})
Created project Launch and added three tasks to it.
```
When you need a capability that doesn't exist, the agent generates a new service mid-conversation:
```
> I need to track shipping. Create a shipment for order 123 to London.
⚡ generating shipping service...
✓ shipping
→ shipping_Shipping_Create({"order_id":"123","destination":"London"})
← {"record":{"id":"xyz...","status":"pending"}}
Created shipment for order 123 going to London.
```
Edit the generated code by hand at any time — re-running preserves your changes. [Read more](https://go-micro.dev/blog/13).
## Why an Agent Harness
The first wave of agent frameworks helped developers put a model in a loop. The next problem is operating that loop: connecting it to real tools, scoping what it can touch, preserving state, routing work to specialists, recovering from failures, observing what happened, and letting other agents call it. That is harness work.
Go Micro's answer is to make the harness the same thing you already deploy:
- **Tools are services** — endpoint metadata becomes tool schema; RPC executes the call.
- **Agents are services** — they register, discover, load-balance, and expose `Agent.Chat`.
- **Workflows are durable code paths** — use flows when the path is known; dispatch to agents when it is not.
- **Safety lives at execution** — `MaxSteps`, `LoopLimit`, `ApproveTool`, and tool wrappers run where actions happen.
- **Interop is built in** — MCP for tools, A2A for agents, x402 for paid tools.
Use Go Micro when the agent has to operate a system, not just answer a prompt.
## Writing Services
Under the hood, a service is a struct with methods. Doc comments and `@example` tags become tool descriptions for AI agents automatically.
```go
package main
import (
"go-micro.dev/v5"
"context"
"go-micro.dev/v6"
)
type Request struct {
Name string `json:"name"`
Name string `json:"name"`
}
type Response struct {
Message string `json:"message"`
Message string `json:"message"`
}
type Say struct{}
// Hello greets a person by name.
// @example {"name": "Alice"}
func (h *Say) Hello(ctx context.Context, req *Request, rsp *Response) error {
rsp.Message = "Hello " + req.Name
return nil
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()
service := micro.NewService("greeter")
service.Handle(new(Say))
service.Run()
}
```
Set a fixed address
Run it and everything is accessible — REST, gRPC, MCP, agent playground:
```bash
micro run
# Dashboard: http://localhost:8080
# API: http://localhost:8080/api/{service}/{method}
# Agent: http://localhost:8080/agent
# MCP Tools: http://localhost:8080/mcp/tools
```
You can also scaffold a service from a template:
```bash
micro new helloworld
micro new contacts --template crud
```
## Building Agents
An Agent is a service with an LLM inside it. It has a proto-defined `Agent.Chat` RPC endpoint, registers in the registry, and is callable like any service:
```go
service := micro.NewService(
micro.Name("helloworld"),
micro.Address(":8080"),
agent := micro.NewAgent("task-mgr",
micro.AgentServices("task", "project"),
micro.AgentPrompt("You manage tasks and projects. You understand deadlines and priorities."),
micro.AgentProvider("anthropic"),
)
agent.Run()
```
The agent discovers its services from the registry, scopes its tools to their endpoints, and maintains conversation memory in the store. It registers itself so `micro chat` and other agents can find it.
```go
// Programmatic interaction
resp, _ := agent.Ask(ctx, "What tasks are overdue?")
fmt.Println(resp.Reply)
```
Multiple agents coordinate via RPC — each is a service with an `Agent.Chat` endpoint. `micro chat` routes to the right one.
```bash
micro agent list # list registered agents
micro call task-mgr Agent.Chat '{"message": "What tasks are overdue?"}'
```
### Plan & Delegate
Every agent gets two built-in harness capabilities, exposed as tools — no extra setup or separate graph runtime:
- **`plan`** — for multi-step work, the agent records an ordered plan in its store-backed memory and stays oriented across turns.
- **`delegate`** — the agent hands a self-contained subtask to another agent. If a registered agent already owns the relevant services, the hand-off goes over RPC to that agent; otherwise a focused, short-lived sub-agent is created for the subtask with its own isolated context.
This keeps intelligence distributed: an agent doesn't need to know *how* to do everything, only *who* does. See [examples/agent-plan-delegate](examples/agent-plan-delegate/).
```go
// A sub-agent is just an agent — created with New, talked to with Ask.
// delegate-first: reuse a registered agent, or spin up a focused one.
resp, _ := agent.Ask(ctx, "Plan the launch, create the tasks, and have comms notify the owner.")
```
### Batteries included, pluggable
Just as a service composes pluggable abstractions (registry, broker, store), an agent composes a **model**, **memory**, and **tools** — sane defaults out of the box, each swappable.
```go
agent := micro.NewAgent("assistant",
micro.AgentProvider("anthropic"), // model — swap the provider
micro.AgentMemory(micro.NewInMemory(50)), // memory — default is store-backed & durable
micro.AgentTool("weather", "Get the weather for a city",
map[string]any{"city": map[string]any{"type": "string"}},
func(ctx context.Context, in map[string]any) (string, error) {
return getWeather(in["city"].(string)) // tools beyond your services — any function
}),
micro.AgentMaxSteps(8), // guardrails
)
```
Call it via curl
**Memory** is durable and store-backed by default (Postgres, NATS KV, or file), so an agent picks up where it left off after a restart — or supply your own with `AgentMemory`. **Tools** are your services automatically, plus any function you register with `AgentTool`.
### Paid tools (x402)
Every endpoint is an AI-callable tool — and it can be a *paid* tool. Go Micro supports [x402](https://x402.org), the HTTP 402 payment standard for agents, so a tool can require a stablecoin payment and an agent can settle it autonomously. It's opt-in and carries no crypto in the framework: verification is delegated to a pluggable facilitator (Coinbase, Alchemy, self-hosted), so Base and Solana are just different facilitators.
```bash
curl -XPOST \
-H 'Content-Type: application/json' \
-H 'Micro-Endpoint: Say.Hello' \
-d '{"name": "alice"}' \
http://localhost:8080
# Charge for tool calls at the MCP gateway (off unless you set a pay-to address)
micro mcp serve --x402-pay-to 0xYourAddress --x402-network solana --x402-amount 10000
# Per-tool amounts via a config file
micro mcp serve --x402-config x402.json
```
## Experimental
See the [Payments (x402) guide](internal/website/docs/guides/x402-payments.md).
There's a new `genai` package for generative AI capabilities.
### Reachable by other agents (A2A)
## Protobuf
Install the code generator and see usage in the docs:
Within a Go Micro system, agents reach each other over RPC. To make them reachable by agents on *other* frameworks, Go Micro speaks the [Agent2Agent (A2A) protocol](https://a2a-protocol.org). The A2A gateway discovers your agents from the registry, generates an Agent Card for each from its metadata — the same way the MCP gateway derives tools from service endpoints — and translates incoming A2A tasks to the agent's `Agent.Chat` RPC. No per-agent code: register an agent and it's reachable over A2A.
```bash
go install go-micro.dev/v5/cmd/protoc-gen-micro@latest
micro a2a serve --address :4000 # gateway: expose every registered agent over A2A
micro a2a list # agents and their Agent Card URLs
```
Docs: [`internal/website/docs/getting-started.md`](internal/website/docs/getting-started.md)
Or skip the gateway entirely — an agent can serve its own A2A endpoint directly, handling tasks in-process:
## Command Line
Install the CLI:
```
go install go-micro.dev/v5/cmd/micro@latest
```go
micro.NewAgent("task-mgr", micro.AgentServices("task"), micro.AgentA2A(":4000"))
```
### Quick Start
It works both ways. To call an agent on another framework, an `a2a.Client` is wired into the two places that hand off work: `flow.A2A(url)` as a workflow step (the cross-framework `Dispatch`), and `delegate` to an `http(s)` URL from inside an agent.
```bash
micro new helloworld # Create a new service
cd helloworld
micro run # Run with API gateway
MCP exposes your services as tools; A2A exposes your agents as agents. See the [A2A guide](internal/website/docs/guides/a2a-protocol.md).
## Features
### AI
| Feature | Details |
|---------|---------|
| Agents | `micro.NewAgent()` — intelligent layer that manages services |
| Plan & delegate | Built-in agent tools — plan multi-step work, delegate subtasks to other agents |
| Pluggable memory | Durable store-backed conversation memory by default; swap with `AgentMemory` |
| Custom tools | `AgentTool` — give an agent any function as a tool, beyond its services |
| Guardrails | `MaxSteps` (stop on count), `LoopLimit` (stop repeated no-progress calls), `ApproveTool` (human-in-the-loop) |
| Tool middleware | `AgentWrapTool` — wrap tool execution for logging, metrics, or retries (like client/server wrappers) |
| Workflows | `micro.NewFlow()` — event-driven; one step, ordered durable steps, or triggers an agent |
| Durable execution | Checkpointed flow steps survive a crash and resume where they stopped; store-backed by default, pluggable backend |
| MCP gateway | Every endpoint is an AI tool automatically |
| A2A gateway | Every agent is reachable over the Agent2Agent protocol; cards generated from the registry (`micro a2a`) |
| Payments (x402) | Opt-in per-call payments for tools via the x402 standard; pluggable facilitator (Base, Solana, …) |
| 7 LLM providers | Anthropic, OpenAI, Gemini, Groq, Mistral, Together, Atlas Cloud |
| Interactive console | `micro run` includes a chat console for talking to services |
| Service generation | `micro run --prompt` — describe a system, get running services |
### Framework
| Feature | Details |
|---------|---------|
| Service registry | mDNS (default), Consul, etcd |
| RPC client/server | gRPC transport, load balancing, streaming |
| Pub/sub events | NATS, RabbitMQ, HTTP broker |
| Key-value store | File (bbolt), Postgres, NATS KV |
| Typed model layer | CRUD + queries, SQLite/Postgres backends |
| Everything swappable | All abstractions are Go interfaces |
### Developer experience & deployment
| Feature | Details |
|---------|---------|
| Hot reload | `micro run` watches files, rebuilds on change |
| Templates | `micro new --template crud/pubsub/api` |
| One-command deploy | `micro deploy user@server` — SSH + systemd, no Docker |
## CLI
| Command | Purpose |
|---------|---------|
| `micro run --prompt "..."` | Generate services + agent, start with interactive console |
| `micro run` | Dev mode: hot reload, gateway, interactive console |
| `micro run -d` | Detached mode (no console) |
| `micro chat` | Standalone chat (when not using micro run) |
| `micro agent list` | List registered agents |
| `micro new myservice` | Scaffold a service |
| `micro call service endpoint '{}'` | Call a service or agent from the CLI |
| `micro build` | Compile production binaries |
| `micro deploy user@server` | Deploy via SSH + systemd |
## Multi-Service Projects
Run multiple services together:
```go
users := micro.NewService("users", micro.Address(":9001"))
orders := micro.NewService("orders", micro.Address(":9002"))
users.Handle(new(Users))
orders.Handle(new(Orders))
g := micro.NewGroup(users, orders)
g.Run()
```
Then open http://localhost:8080 to see your service and call it from the browser.
### micro run
`micro run` starts your services with:
- **API Gateway** - HTTP to RPC proxy at `/api/{service}/{method}`
- **Web Dashboard** - Browse and call services at `/`
- **Health Checks** - Aggregated health at `/health`
- **Hot Reload** - Auto-rebuild on file changes
```bash
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:
Or use a `micro.mu` config file:
```
service users
path ./users
port 8081
service posts
path ./posts
port 8082
service orders
path ./orders
depends users
env development
DATABASE_URL sqlite://./dev.db
```
The gateway runs on :8080 by default, so services should use other ports.
## Data Model
### Deployment
Typed persistence with CRUD and queries:
```bash
micro build # Build container images
micro build --compose # Generate docker-compose.yml
micro deploy # Deploy with docker-compose
micro deploy --ssh user@host # Deploy via SSH
```go
type User struct {
ID string `json:"id" model:"key"`
Name string `json:"name"`
Email string `json:"email" model:"index"`
}
db := service.Model()
db.Register(&User{})
db.Create(ctx, &User{ID: "1", Name: "Alice", Email: "alice@example.com"})
var results []*User
db.List(ctx, &results, model.Where("email", "alice@example.com"))
```
See [cmd/micro/README.md](cmd/micro/README.md) for full CLI documentation.
Backends: memory (default), SQLite, Postgres.
Docs: [`internal/website/docs`](internal/website/docs)
## AI Providers
Package reference: https://pkg.go.dev/go-micro.dev/v5
Swap providers with a single import — same interface everywhere:
Selected topics:
- Getting Started: [`internal/website/docs/getting-started.md`](internal/website/docs/getting-started.md)
- Plugins overview: [`internal/website/docs/plugins.md`](internal/website/docs/plugins.md)
- Learn by Example: [`internal/website/docs/examples/index.md`](internal/website/docs/examples/index.md)
| Provider | Default Model |
|----------|---------------|
| Anthropic | `claude-sonnet-4-20250514` |
| OpenAI | `gpt-4o` |
| Google Gemini | `gemini-2.5-flash` |
| Groq | `llama-3.3-70b-versatile` |
| Mistral | `mistral-large-latest` |
| Together AI | `Llama-3.3-70B-Instruct-Turbo` |
| Atlas Cloud | `llama-3.3-70b` |
## Adopters
```go
m := ai.New("anthropic", ai.WithAPIKey(key))
resp, _ := m.Generate(ctx, &ai.Request{Prompt: "hello"})
```
- [Sourse](https://sourse.eu) - Work in the field of earth observation, including embedded Kubernetes running onboard aircraft, and weve built a mission management SaaS platform using Go Micro.
## Examples
- [hello-world](examples/hello-world/) — Basic RPC service
- [multi-service](examples/multi-service/) — Multiple services in one binary
- [mcp](examples/mcp/) — MCP integration with AI agents
- [agent-plan-delegate](examples/agent-plan-delegate/) — Agent planning and multi-agent delegation
- [grpc-interop](examples/grpc-interop/) — Call go-micro from any gRPC client
See [all examples](examples/README.md).
## Docs
- [Getting Started](internal/website/docs/getting-started.md)
- [AI Integration](internal/website/docs/ai-integration.md)
- [Agents and Workflows](internal/website/docs/guides/agents-and-workflows.md)
- [Agent Design](internal/docs/AGENT_DESIGN.md)
- [Plan & Delegate](internal/website/docs/guides/plan-delegate.md)
- [Agent Guardrails](internal/website/docs/guides/agent-guardrails.md)
- [Payments (x402)](internal/website/docs/guides/x402-payments.md)
- [MCP & AI Agents](internal/website/docs/mcp.md)
- [Data Model](internal/website/docs/model.md)
- [Deployment](internal/website/docs/deployment.md)
- [Plugins](internal/website/docs/plugins.md)
Package reference: https://pkg.go.dev/go-micro.dev/v6
+56 -141
View File
@@ -1,163 +1,78 @@
# Go Micro Roadmap
This roadmap outlines the planned features and improvements for Go Micro. Community feedback and contributions are welcome!
Go Micro is an **agent harness** and service framework for Go. A harness is the
runtime around an agent — the tools, memory, guardrails, workflows, state,
discovery, and protocols it needs to operate a system rather than just answer a
prompt. An agent is a distributed system — it discovers services, calls them,
holds state, and recovers from failure — so the harness is the runtime services
already have, and building an agent is building a service. The roadmap has two
jobs: make **agentic development** excellent, and make the **developer experience**
around it excellent.
## Current Focus (Q1 2026)
The full, current roadmap lives at **[go-micro.dev/docs/roadmap](https://go-micro.dev/docs/roadmap)**
([source](internal/website/docs/roadmap.md)). The highlights:
### Documentation & Developer Experience
- [x] Modernize documentation structure
- [x] Add learn-by-example guides
- [x] Update issue templates
- [ ] Create video tutorials
- [ ] Interactive documentation site
- [ ] Plugin discovery dashboard
## Where we are (v6)
### Observability
- [ ] OpenTelemetry native support
- [ ] Auto-instrumentation for handlers
- [ ] Metrics export standardization
- [ ] Distributed tracing examples
- [ ] Integration with popular observability platforms
Services, agents (`plan`/`delegate`, guardrails, memory, tool middleware), durable
flows, the MCP and A2A gateways (both directions), x402 paid tools, secure by
default.
### Developer Tools
- [ ] `micro dev` with hot reload
- [ ] Service templates (`micro new --template`)
- [ ] Better error messages with suggestions
- [ ] Debug tooling improvements
- [ ] VS Code extension for Go Micro
## Principles
## Q2 2026
1. Build into what people run, never a separate product (no hosted platform, no
enterprise edition, no VC).
2. CLI-first — the CLI is the experience; UI must earn its place, never bloat.
3. The getting-started flow is a contract: *0→1* (scaffold → run → call) and
*0→hero* (a working multi-agent system) must always work and are verified on
every change.
4. Interaction matters as much as running — chatting with agents, inspecting runs
and history, end to end.
5. Battle-tested: works across every provider, fails safely, observable.
### Production Readiness
- [ ] Health check standardization
- [ ] Graceful shutdown improvements
- [ ] Resource cleanup best practices
- [ ] Load testing framework integration
- [ ] Performance benchmarking suite
## Now — hardening
### Cloud Native
- [ ] Kubernetes operator
- [ ] Helm charts for common setups
- [ ] Service mesh integration guides (Istio, Linkerd)
- [ ] Cloud provider quickstarts (AWS, GCP, Azure)
- [ ] Multi-cluster patterns
- **Cross-provider conformance** — the same agent scenario across all seven
providers, gated on keys, on a schedule.
- **Failure & resilience** — timeouts, rate limits, cancellation, deadline/context
propagation, retry/backoff.
- **Getting-started contract** — define and CI-verify the 0→1 and 0→hero flows.
### Security
- [ ] mTLS by default option
- [ ] Secret management integration (Vault, AWS Secrets Manager)
- [ ] RBAC improvements
- [ ] Security audit and hardening
- [ ] CVE scanning and response process
## Next — agentic depth
## Q3 2026
- **Durable agent loop** — resume a long run via `Checkpoint` (flows already do).
- **Streaming** — `ai.Stream` + A2A `message/stream`, end to end.
- **Agent observability** — `RunInfo` → OpenTelemetry spans.
### Plugin Ecosystem
- [ ] Plugin marketplace/registry
- [ ] Plugin quality standards
- [ ] Community plugin contributions
- [ ] Plugin compatibility matrix
- [ ] Auto-discovery of available plugins
## Later
### Streaming & Async
- [ ] Improved streaming support
- [ ] Server-sent events (SSE) support
- [ ] WebSocket plugin
- [ ] Event sourcing patterns
- [ ] CQRS examples
- Memory management (summarization, retrieval/RAG); human-in-the-loop pause/resume;
x402 live-facilitator conformance and paid remote tools with spend caps; A2A
streaming, push notifications, and multi-turn tasks.
### Testing
- [ ] Mock generation tooling
- [ ] Integration test helpers
- [ ] Contract testing support
- [ ] Chaos engineering examples
- [ ] E2E testing framework
## Developer experience (ongoing)
## Q4 2026
- A seamless CLI inner loop (scaffold → run → chat → inspect → deploy); UI
discipline (trim what isn't great); a maintained real-world example that doubles
as the 0→hero reference; docs kept in lockstep with the code.
### Performance
- [ ] Connection pooling optimizations
- [ ] Zero-allocation paths
- [ ] gRPC performance improvements
- [ ] Caching strategies guide
- [ ] Performance profiling tools
## How it's sustained
### Developer Productivity
- [ ] Code generation improvements
- [ ] Better IDE support
- [ ] Debugging tools
- [ ] Migration automation tools
- [ ] Upgrade helpers
The framework is the product, funded by sponsorship from those who run it — not a
hosted service, enterprise tier, or venture funding. See
[the v6 story](https://go-micro.dev/blog/27).
### Community
- [ ] Regular blog posts and case studies
- [ ] Community spotlight program
- [ ] Contribution rewards
- [ ] Monthly community calls
- [ ] Conference presence
## Contributing & feedback
## Long-term Vision
Pick an item, open an issue to discuss the approach, and submit a PR. Or join the
[Discord](https://discord.gg/WeMU5AGxD). Include tests, run `make test` and
`make lint`.
### Core Framework
- Maintain backward compatibility (Go Micro v5+)
- Progressive disclosure of complexity
- Best-in-class developer experience
- Production-grade reliability
- Comprehensive plugin ecosystem
## Version support
### Ecosystem Goals
- 100+ production deployments documented
- 50+ community plugins
- Active contributor community
- Regular releases (monthly patches, quarterly features)
- Comprehensive benchmarks vs alternatives
- **v6** — active development (current).
- **v5** — security fixes only.
- **v4 and earlier** — end of life.
### Differentiation
- **Batteries included, fully swappable** - Start simple, scale complex
- **Zero-config local development** - No infrastructure required to start
- **Plugin ecosystem in-repo** - No version compatibility hell
- **Progressive complexity** - Learn as you grow
- **Cloud-native first** - Built for Kubernetes and containers
## Contributing
We welcome contributions to any roadmap items! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
### High Priority Areas
1. Documentation improvements
2. Real-world examples
3. Plugin development
4. Performance optimizations
5. Testing infrastructure
### How to Contribute
- Pick an item from the roadmap
- Open an issue to discuss approach
- Submit a PR with implementation
- Help review others' contributions
## Feedback
Have suggestions for the roadmap?
- Open a [feature request](.github/ISSUE_TEMPLATE/feature_request.md)
- Start a discussion in GitHub Discussions
- Comment on existing roadmap issues
## Version Compatibility
We follow semantic versioning:
- Major versions (v5 → v6): Breaking changes
- Minor versions (v5.3 → v5.4): New features, backward compatible
- Patch versions (v5.3.0 → v5.3.1): Bug fixes, no API changes
## Support Timeline
- v5: Active development (current)
- v4: Security fixes only (until v6 release)
- v3: End of life
---
Last updated: November 2025
This roadmap is subject to change based on community needs and priorities. Star the repo to stay updated! ⭐
Major versions (v5 → v6) carry breaking changes; minors are backward-compatible.
See the [v5 → v6 migration guide](https://go-micro.dev/docs/guides/migration/v5-to-v6).
+179
View File
@@ -0,0 +1,179 @@
# Security Policy
## Supported Versions
We actively support the following versions of go-micro:
| Version | Supported |
| ------- | ------------------ |
| 5.x | :white_check_mark: |
| 4.x | :x: |
| 3.x | :x: |
| < 3.0 | :x: |
## Reporting a Vulnerability
**Please do not report security vulnerabilities through public GitHub issues.**
### How to Report
Send security vulnerability reports to: **security@go-micro.dev**
Or use GitHub's private security advisory feature:
https://github.com/micro/go-micro/security/advisories/new
### What to Include
Please include as much of the following information as possible:
- Type of vulnerability (e.g., RCE, XSS, SQL injection, etc.)
- Full paths of source file(s) related to the vulnerability
- Location of the affected source code (tag/branch/commit or direct URL)
- Step-by-step instructions to reproduce the issue
- Proof-of-concept or exploit code (if possible)
- Impact of the issue, including how an attacker might exploit it
### Response Timeline
- **Acknowledgment**: Within 48 hours
- **Initial Assessment**: Within 5 business days
- **Fix Timeline**: Depends on severity
- Critical: 7 days
- High: 14 days
- Medium: 30 days
- Low: Next release cycle
### Disclosure Policy
- We follow **coordinated disclosure**
- We'll work with you to understand and fix the issue
- We'll credit you in the security advisory (unless you prefer to remain anonymous)
- Please give us reasonable time to fix before public disclosure
- We'll publish a security advisory on GitHub when the fix is released
## Security Best Practices
When using go-micro in production:
### TLS/Transport Security
```go
import "go-micro.dev/v5/transport"
// Enable TLS verification (recommended)
os.Setenv("MICRO_TLS_SECURE", "true")
// Or use SecureConfig explicitly
tlsConfig := transport.SecureConfig()
```
See [TLS Security Update](internal/website/docs/TLS_SECURITY_UPDATE.md) for details.
### Authentication
```go
import "go-micro.dev/v5/auth"
// Use JWT authentication
service := micro.NewService(
micro.Auth(auth.NewAuth()),
)
```
### Input Validation
Always validate and sanitize inputs in your handlers:
```go
func (h *Handler) Create(ctx context.Context, req *Request, rsp *Response) error {
// Validate input
if req.Name == "" {
return errors.BadRequest("handler.create", "name is required")
}
// Sanitize and process
// ...
}
```
### Rate Limiting
Implement rate limiting for public-facing services:
```go
import "go-micro.dev/v5/client"
// Client-side rate limiting
client.NewClient(
client.RequestTimeout(time.Second * 5),
client.Retries(3),
)
```
### Secrets Management
Never commit secrets to version control:
```go
// Good: Use environment variables
apiKey := os.Getenv("API_KEY")
// Better: Use a secrets manager
import "github.com/hashicorp/vault/api"
```
### Dependency Security
Regularly update dependencies:
```bash
# Check for vulnerabilities
go list -json -m all | nancy sleuth
# Update dependencies
go get -u ./...
go mod tidy
```
## Known Security Considerations
### Reflection Usage
go-micro uses reflection for automatic handler registration. While this is a deliberate design choice for developer productivity, be aware:
- Type safety is enforced at runtime, not compile time
- Malformed requests won't crash services (errors are returned)
- See [Performance Considerations](internal/website/docs/performance.md)
### TLS Certificate Verification
**Default behavior in v5**: TLS certificate verification is **disabled** for backward compatibility.
**Production recommendation**: Enable secure mode:
```bash
export MICRO_TLS_SECURE=true
```
This will be the default in v6.
## Security Updates
Security updates are published as:
- GitHub Security Advisories
- Release notes with `[SECURITY]` prefix
- CVE entries for critical issues
Subscribe to releases: https://github.com/micro/go-micro/releases
## Bug Bounty
We currently do not offer a bug bounty program, but we greatly appreciate responsible disclosure and will publicly credit researchers who report valid security issues.
## Questions?
For security questions that are not vulnerabilities, please:
- Open a discussion: https://github.com/micro/go-micro/discussions
- Join Discord: https://discord.gg/WeMU5AGxD
- Email: support@go-micro.dev
+29
View File
@@ -0,0 +1,29 @@
# Support
Go Micro is free and open source. There are two ways to get help: the community, and commercial support.
## Community support (free)
- **Documentation** — https://go-micro.dev/docs
- **Examples** — https://github.com/micro/go-micro/tree/master/examples
- **Bugs & features** — https://github.com/micro/go-micro/issues
- **Questions** — open a [Question](https://github.com/micro/go-micro/issues/new?template=question.md) issue
Community support is best-effort, from maintainers and contributors, with no response-time guarantees.
## Commercial support
If you're running Go Micro in production — or building agents and services on it and want a hand — paid support and consulting are available directly from the maintainer. This is what keeps the project maintained.
| Tier | For | What you get | How |
|------|-----|--------------|-----|
| **Community** | Everyone | Docs, examples, issues — best-effort | Free |
| **Sponsor** | Individuals & companies who rely on Go Micro | Back ongoing development; your name/logo in the README and on the site; a voice in priorities | [GitHub Sponsors](https://github.com/sponsors/asim) |
| **Support** | Teams running Go Micro in production | Priority responses, a direct line to the maintainer, prioritized bug fixes, upgrade & integration help | [Open a request](#get-in-touch) |
| **Consulting** | Teams building on Go Micro | Hands-on integration, architecture & agent-design review, training & onboarding, sponsored features | [Open a request](#get-in-touch) |
Recurring amounts are set on the [Sponsors page](https://github.com/sponsors/asim); support and consulting are scoped and quoted per engagement.
## Get in touch
Open a [**Commercial Support / Consulting**](https://github.com/micro/go-micro/issues/new?template=commercial_support.md) request — tell us what you're building, what you need, and your timeline, and we'll follow up. For anything you'd rather not discuss in public, become a [sponsor](https://github.com/sponsors/asim) and message privately.
+365
View File
@@ -0,0 +1,365 @@
// Package agent provides the Agent abstraction for Go Micro.
//
// An Agent is a service with an LLM inside it. It registers a Chat
// RPC endpoint, discovers its assigned services' tools, and
// orchestrates them intelligently.
//
// agent := micro.NewAgent("task-mgr",
// micro.AgentServices("task"),
// micro.AgentPrompt("You manage tasks."),
// micro.AgentProvider("anthropic"),
// )
// agent.Run()
package agent
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"github.com/google/uuid"
pb "go-micro.dev/v6/agent/proto"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/gateway/a2a"
"go-micro.dev/v6/server"
"go-micro.dev/v6/store"
_ "go-micro.dev/v6/ai/anthropic"
_ "go-micro.dev/v6/ai/atlascloud"
_ "go-micro.dev/v6/ai/gemini"
_ "go-micro.dev/v6/ai/groq"
_ "go-micro.dev/v6/ai/mistral"
_ "go-micro.dev/v6/ai/openai"
_ "go-micro.dev/v6/ai/together"
)
// Agent is the interface for an AI agent that manages services.
type Agent interface {
Name() string
Init(...Option)
Options() Options
Ask(ctx context.Context, message string) (*Response, error)
Run() error
Stop() error
String() string
}
// Response is what an agent returns from Chat.
type Response struct {
Reply string
ToolCalls []ai.ToolCall
Agent string
// RunID correlates this Ask with tool calls, trace spans, and the
// persisted run timeline. ParentID is set when this response belongs
// to a delegated sub-agent run.
RunID string
ParentID string
}
type agentImpl struct {
opts Options
model ai.Model
tools *ai.Tools
mem Memory
server server.Server
mu sync.Mutex
// ephemeral marks a short-lived sub-agent created by delegation.
// Ephemeral agents run with an isolated context: they load and
// persist no history, and have no built-in tools (so they cannot
// plan or re-delegate).
ephemeral bool
// steps counts tool executions in the current Ask, for MaxSteps.
steps int
// calls counts identical tool calls (name+args) in the current Ask,
// for LoopLimit.
calls map[string]int
// runID correlates the tool calls of the current Ask; parentRunID is
// the run that delegated to this one (set on ephemeral sub-agents).
// Both are surfaced to tool wrappers via ai.RunInfo on the context.
runID string
parentRunID string
}
// New creates a new Agent.
func New(opts ...Option) Agent {
return &agentImpl{
opts: newOptions(opts...),
}
}
// newEphemeral creates a short-lived sub-agent for a delegated subtask.
// It shares the parent's provider, model, and infrastructure but runs
// with an isolated context: it loads and persists no history and has no
// built-in tools (so it can neither plan nor re-delegate). Returns the
// concrete type because ephemeral is an internal construction detail,
// not a public option.
func newEphemeral(opts ...Option) *agentImpl {
return &agentImpl{
opts: newOptions(opts...),
ephemeral: true,
}
}
func (a *agentImpl) Name() string {
return a.opts.Name
}
func (a *agentImpl) Init(opts ...Option) {
for _, o := range opts {
o(&a.opts)
}
a.setup()
}
func (a *agentImpl) Options() Options {
return a.opts
}
func (a *agentImpl) String() string {
return "agent"
}
func (a *agentImpl) setup() {
var modelOpts []ai.Option
modelOpts = append(modelOpts, ai.WithAPIKey(a.opts.APIKey))
if a.opts.Model != "" {
modelOpts = append(modelOpts, ai.WithModel(a.opts.Model))
}
a.tools = ai.NewTools(a.opts.Registry, ai.ToolClient(a.opts.Client))
modelOpts = append(modelOpts, ai.WithToolHandler(a.toolHandler()))
a.model = ai.New(a.opts.Provider, modelOpts...)
if a.opts.TraceProvider != nil && a.model != nil {
a.model = a.tracedModel(a.model)
}
// Memory is pluggable. Use the configured one, otherwise the default
// store-backed memory — except ephemeral sub-agents, which keep an
// isolated, non-persistent context.
switch {
case a.opts.Memory != nil:
a.mem = a.opts.Memory
case a.ephemeral:
a.mem = NewInMemory(a.opts.HistoryLimit)
default:
a.mem = NewMemory(a.stateStore(), "history", a.opts.HistoryLimit)
}
}
// stateStore returns the agent's own state store, scoped to its name so
// memory and plan live in their own table ("agent/{name}") rather than a
// shared global one. The scoped handle injects the database/table per
// operation without mutating the underlying store.
func (a *agentImpl) stateStore() store.Store {
s := a.opts.Store
if s == nil {
s = store.DefaultStore
}
return store.Scope(s, "agent", a.opts.Name)
}
// Ask sends a message and returns the agent's response.
// This is the programmatic API for direct use.
func (a *agentImpl) Ask(ctx context.Context, message string) (*Response, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.model == nil {
a.setup()
}
toolList, err := a.discoverTools()
if err != nil {
return nil, fmt.Errorf("discover tools: %w", err)
}
a.mem.Add("user", message)
a.steps = 0
a.calls = map[string]int{}
// Correlate this run's tool calls and surface lineage to wrappers.
a.runID = uuid.New().String()
ctx = ai.WithRunInfo(ctx, ai.RunInfo{
RunID: a.runID,
ParentID: a.parentRunID,
Agent: a.opts.Name,
})
ctx, endRun := a.startRun(ctx, message)
defer func() { endRun(err) }()
resp, err := ai.GenerateWithRetry(ctx, a.model, &ai.Request{
Prompt: message,
SystemPrompt: a.buildPrompt(),
Tools: toolList,
Messages: a.mem.Messages(),
}, ai.GeneratePolicy{
Timeout: a.opts.ModelTimeout,
MaxAttempts: a.opts.ModelMaxAttempts,
Backoff: a.opts.ModelRetryBackoff,
})
if err != nil {
return nil, err
}
if resp.Reply != "" {
a.mem.Add("assistant", resp.Reply)
}
if resp.Answer != "" {
a.mem.Add("assistant", resp.Answer)
}
reply := resp.Reply
if resp.Answer != "" {
if reply != "" {
reply += "\n\n"
}
reply += resp.Answer
}
return &Response{
Reply: reply,
ToolCalls: resp.ToolCalls,
Agent: a.opts.Name,
RunID: a.runID,
ParentID: a.parentRunID,
}, nil
}
// Chat implements the proto AgentHandler interface for RPC.
// @example {"message": "What tasks are overdue?"}
func (a *agentImpl) Chat(ctx context.Context, req *pb.ChatRequest, rsp *pb.ChatResponse) error {
resp, err := a.Ask(ctx, req.Message)
if err != nil {
return err
}
rsp.Reply = resp.Reply
rsp.Agent = resp.Agent
for _, tc := range resp.ToolCalls {
input, _ := json.Marshal(tc.Input)
rsp.ToolCalls = append(rsp.ToolCalls, &pb.ToolCall{
Id: tc.ID,
Name: tc.Name,
Input: string(input),
Result: tc.Result,
})
}
return nil
}
// Run starts the agent as a service with a Chat RPC endpoint.
func (a *agentImpl) Run() error {
if a.model == nil {
a.setup()
}
a.server = server.NewServer(
server.Name(a.opts.Name),
server.Registry(a.opts.Registry),
server.Metadata(map[string]string{
"type": "agent",
"services": strings.Join(a.opts.Services, ","),
}),
)
_ = pb.RegisterAgentHandler(a.server, a)
if err := a.server.Start(); err != nil {
return fmt.Errorf("failed to start agent: %w", err)
}
fmt.Printf("Agent %s registered (manages: %s)\n", a.opts.Name, strings.Join(a.opts.Services, ", "))
// Optionally serve the agent directly over the A2A protocol, calling
// Ask in-process — no separate gateway needed to be queried by URL.
if a.opts.A2AAddress != "" {
card := a2a.Card(a.opts.Name, "http://localhost"+a.opts.A2AAddress, "", a.opts.Services)
handler := a2a.NewAgentHandler(card, func(ctx context.Context, text string) (string, error) {
resp, err := a.Ask(ctx, text)
if err != nil {
return "", err
}
return resp.Reply, nil
})
go func() {
if err := http.ListenAndServe(a.opts.A2AAddress, handler); err != nil {
fmt.Printf("agent %s A2A server: %v\n", a.opts.Name, err)
}
}()
fmt.Printf("Agent %s serving A2A on %s\n", a.opts.Name, a.opts.A2AAddress)
}
ch := make(chan struct{})
<-ch
return nil
}
func (a *agentImpl) Stop() error {
if a.server != nil {
return a.server.Stop()
}
return nil
}
func (a *agentImpl) discoverTools() ([]ai.Tool, error) {
all, err := a.tools.Discover()
if err != nil {
return nil, err
}
var scoped []ai.Tool
for _, t := range all {
if strings.HasPrefix(t.OriginalName, a.opts.Name+".") {
continue
}
if len(a.opts.Services) == 0 {
scoped = append(scoped, t)
continue
}
for _, svc := range a.opts.Services {
if strings.HasPrefix(t.OriginalName, svc+".") {
scoped = append(scoped, t)
break
}
}
}
// Developer-registered custom tools (WithTool).
for i := range a.opts.tools {
scoped = append(scoped, a.opts.tools[i].def)
}
// Expose the agent's own capabilities (plan, delegate) as tools.
// Ephemeral sub-agents don't get them.
if !a.ephemeral {
scoped = append(scoped, builtinTools()...)
}
return scoped, nil
}
func (a *agentImpl) buildPrompt() string {
var base string
switch {
case a.opts.Prompt != "":
base = a.opts.Prompt
case len(a.opts.Services) > 0:
base = fmt.Sprintf("You are the %s agent. You manage these services: %s. Use the available tools to fulfill requests.",
a.opts.Name, strings.Join(a.opts.Services, ", "))
default:
base = fmt.Sprintf("You are the %s agent. Use the available tools to fulfill requests.", a.opts.Name)
}
// Keep the agent oriented: surface its saved plan, if any.
if !a.ephemeral {
if plan := a.loadPlan(); plan != "" {
base += "\n\nYour current plan (update it with the plan tool as you make progress):\n" + plan
}
}
return base
}
+88
View File
@@ -0,0 +1,88 @@
package agent
import (
"testing"
)
func TestNew(t *testing.T) {
a := New(
Name("test-agent"),
Services("task", "project"),
Prompt("You manage tasks."),
Provider("anthropic"),
)
if a.Name() != "test-agent" {
t.Errorf("Name() = %q, want %q", a.Name(), "test-agent")
}
opts := a.Options()
if opts.Provider != "anthropic" {
t.Errorf("Provider = %q, want %q", opts.Provider, "anthropic")
}
if len(opts.Services) != 2 {
t.Fatalf("Services = %v, want 2 items", opts.Services)
}
if opts.Services[0] != "task" || opts.Services[1] != "project" {
t.Errorf("Services = %v, want [task project]", opts.Services)
}
if opts.Prompt != "You manage tasks." {
t.Errorf("Prompt = %q, want %q", opts.Prompt, "You manage tasks.")
}
if opts.HistoryLimit != 50 {
t.Errorf("HistoryLimit = %d, want 50", opts.HistoryLimit)
}
}
func TestBuildPrompt(t *testing.T) {
// Custom prompt
a := New(Name("test"), Prompt("custom prompt")).(*agentImpl)
if got := a.buildPrompt(); got != "custom prompt" {
t.Errorf("buildPrompt() = %q, want %q", got, "custom prompt")
}
// Auto-generated prompt with services
a = New(Name("test"), Services("task", "project")).(*agentImpl)
got := a.buildPrompt()
if got == "" {
t.Error("buildPrompt() returned empty")
}
if !contains(got, "task") || !contains(got, "project") {
t.Errorf("buildPrompt() = %q, should mention services", got)
}
// Auto-generated prompt without services
a = New(Name("test")).(*agentImpl)
got = a.buildPrompt()
if !contains(got, "test") {
t.Errorf("buildPrompt() = %q, should mention agent name", got)
}
}
func TestDefaults(t *testing.T) {
a := New(Name("test"))
opts := a.Options()
if opts.Registry == nil {
t.Error("Registry should default to DefaultRegistry")
}
if opts.Client == nil {
t.Error("Client should default to DefaultClient")
}
if opts.Store == nil {
t.Error("Store should default to DefaultStore")
}
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (s == sub || len(s) > 0 && containsStr(s, sub))
}
func containsStr(s, sub string) bool {
for i := 0; i <= len(s)-len(sub); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}
+342
View File
@@ -0,0 +1,342 @@
package agent
import (
"context"
"encoding/json"
"fmt"
"strings"
"go-micro.dev/v6/ai"
codecBytes "go-micro.dev/v6/codec/bytes"
"go-micro.dev/v6/gateway/a2a"
"go-micro.dev/v6/store"
)
// Built-in agent tools. These are not service endpoints — they are
// capabilities the agent has over itself: maintaining a plan in its
// memory, and delegating a subtask to another agent.
//
// They are plain tools, wired into the agent's tool handler alongside
// the discovered service tools. There is no separate harness or graph:
// the LLM calls them like any other tool.
const (
toolPlan = "plan"
toolDelegate = "delegate"
)
// builtinTools returns the tool definitions exposed to the model in
// addition to the agent's scoped service tools.
func builtinTools() []ai.Tool {
return []ai.Tool{
{
Name: toolPlan,
OriginalName: toolPlan,
Description: "Record or update your plan as an ordered list of steps before doing multi-step work. " +
"Call this whenever the plan changes. The plan is saved to your memory and shown back to you on later turns.",
Properties: map[string]any{
"steps": map[string]any{
"type": "array",
"description": "Ordered plan steps. Each step has a 'task' (string) and a " +
"'status' (one of: pending, in_progress, done).",
},
},
},
{
Name: toolDelegate,
OriginalName: toolDelegate,
Description: "Delegate a self-contained subtask to another agent. If 'to' names an agent that already " +
"manages the relevant services, that agent handles it; otherwise a focused sub-agent is created for the " +
"subtask. The sub-agent works in an isolated context and returns only its result. Use this to keep your " +
"own context focused and to let domain experts handle their own services.",
Properties: map[string]any{
"task": map[string]any{
"type": "string",
"description": "The subtask to delegate, described completely and self-contained.",
},
"to": map[string]any{
"type": "string",
"description": "Optional. The agent or service name best suited to the subtask, or the URL of an external agent that speaks the A2A protocol.",
},
},
},
}
}
// Builtins returns the built-in agent tools (plan, delegate) together
// with a handler for them, so the same capabilities can be wired into a
// tool loop that isn't a running Agent — for example the `micro chat`
// fallback. The handler's third return value is false when the name is
// not a built-in, so callers can fall through to their own tools.
//
// Configure it with the same options as an Agent (Name, Provider,
// WithStore, WithRegistry, WithClient, ...); these back plan's memory
// and delegate's RPC/sub-agent behavior.
func Builtins(opts ...Option) (tools []ai.Tool, handle func(name string, input map[string]any) (result any, content string, ok bool)) {
a := &agentImpl{opts: newOptions(opts...)}
handle = func(name string, input map[string]any) (any, string, bool) {
switch name {
case toolPlan:
r := a.handlePlan(ai.ToolCall{Name: name, Input: input})
return r.Value, r.Content, true
case toolDelegate:
r := a.handleDelegate(context.Background(), ai.ToolCall{Name: name, Input: input})
return r.Value, r.Content, true
}
return nil, "", false
}
return builtinTools(), handle
}
// toolHandler returns the agent's tool-call handler, composed as a stack
// of wrappers around a base handler — the same middleware shape as
// client/server wrappers. The base executes the call (custom tools,
// delegate, or RPC); the built-in guardrails wrap it; developer wrappers
// (WrapTool) wrap those, outermost, so they observe every call and its
// result including guardrail refusals. Ephemeral sub-agents get the bare
// service handler so they can neither plan nor re-delegate (which
// prevents runaway recursion).
func (a *agentImpl) toolHandler() ai.ToolHandler {
if a.ephemeral {
return a.tools.Handler()
}
// Innermost first: base, then guardrails (approve → loop → step →
// plan), then developer wrappers outermost. Wrapping reverses order,
// so the result runs plan → step → loop → approve → base.
h := a.baseHandler()
h = a.approveWrap(h)
h = a.loopWrap(h)
h = a.stepWrap(h)
h = a.planWrap(h)
h = a.traceTool(h)
for i := len(a.opts.wrappers) - 1; i >= 0; i-- {
h = a.opts.wrappers[i](h)
}
return h
}
// baseHandler executes a tool call: a developer custom tool, the built-in
// delegate, or an RPC to the service. It is the innermost handler.
func (a *agentImpl) baseHandler() ai.ToolHandler {
rpc := a.tools.Handler()
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
for i := range a.opts.tools {
if a.opts.tools[i].def.Name == call.Name {
out, err := a.opts.tools[i].handler(ctx, call.Input)
if err != nil {
return errResult(call.ID, err.Error())
}
return ai.ToolResult{ID: call.ID, Value: out, Content: out}
}
}
if call.Name == toolDelegate {
return a.handleDelegate(ctx, call)
}
return rpc(ctx, call)
}
}
// planWrap handles the plan tool inline. plan is internal bookkeeping,
// not an action — it is never counted, loop-checked, or gated.
func (a *agentImpl) planWrap(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
if call.Name == toolPlan {
return a.handlePlan(call)
}
return next(ctx, call)
}
}
// stepWrap bounds the number of actions per Ask (MaxSteps).
func (a *agentImpl) stepWrap(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
if a.opts.MaxSteps > 0 {
a.steps++
if a.steps > a.opts.MaxSteps {
return refused(call.ID, ai.RefusedMaxSteps, fmt.Sprintf(
"step limit reached (%d). Do not call any more tools; stop and summarize what you have so far.",
a.opts.MaxSteps))
}
}
return next(ctx, call)
}
}
// loopWrap stops the agent repeating an identical action that makes no
// progress (which the step count alone won't catch).
func (a *agentImpl) loopWrap(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
if a.opts.LoopLimit > 0 {
if a.calls == nil {
a.calls = map[string]int{}
}
args, _ := json.Marshal(call.Input)
fp := call.Name + ":" + string(args)
a.calls[fp]++
if a.calls[fp] > a.opts.LoopLimit {
return refused(call.ID, ai.RefusedLoop, fmt.Sprintf(
"loop detected: you have already called %q with the same arguments %d times and the result will not change. Stop repeating it — try a different approach, or finish with what you have.",
call.Name, a.opts.LoopLimit))
}
}
return next(ctx, call)
}
}
// approveWrap gates each action before it runs (ApproveTool).
func (a *agentImpl) approveWrap(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
if a.opts.Approve != nil {
if ok, reason := a.opts.Approve(call.Name, call.Input); !ok {
msg := "tool call was not approved"
if reason != "" {
msg += ": " + reason
}
return refused(call.ID, ai.RefusedApproval, msg)
}
}
return next(ctx, call)
}
}
// handlePlan persists the supplied plan to the agent's memory and
// echoes it back so the model can see the stored state.
func (a *agentImpl) handlePlan(call ai.ToolCall) ai.ToolResult {
data, err := json.Marshal(call.Input)
if err != nil {
return errResult(call.ID, "invalid plan: "+err.Error())
}
_ = a.stateStore().Write(&store.Record{Key: planKey, Value: data})
return ai.ToolResult{ID: call.ID, Value: call.Input, Content: string(data)}
}
// handleDelegate hands a subtask to another agent. Delegate-first:
// if 'to' names a registered agent, it is called via RPC. Otherwise an
// ephemeral sub-agent is created with a fresh, isolated context, asked
// the subtask, and its reply returned.
func (a *agentImpl) handleDelegate(ctx context.Context, call ai.ToolCall) ai.ToolResult {
input := call.Input
task, _ := input["task"].(string)
if task == "" {
return errResult(call.ID, "task is required")
}
to, _ := input["to"].(string)
// An external agent on another framework, addressed by A2A URL.
if strings.HasPrefix(to, "http://") || strings.HasPrefix(to, "https://") {
reply, err := a2a.NewClient(to).Send(ctx, task)
if err != nil {
return errResult(call.ID, "delegate to A2A agent "+to+": "+err.Error())
}
out := map[string]any{"agent": to, "reply": reply}
b, _ := json.Marshal(out)
return ai.ToolResult{ID: call.ID, Value: out, Content: string(b)}
}
// Delegate-first: an existing agent that owns the domain handles it.
if to != "" && a.isAgent(to) {
reply, err := a.callAgentRPC(ctx, to, task)
if err != nil {
return errResult(call.ID, "delegate to agent "+to+": "+err.Error())
}
out := map[string]any{"agent": to, "reply": reply}
b, _ := json.Marshal(out)
return ai.ToolResult{ID: call.ID, Value: out, Content: string(b)}
}
// Otherwise create a focused, ephemeral sub-agent. Fresh context:
// it loads no history and persists none.
var svcs []string
if to != "" {
svcs = []string{to}
}
sub := newEphemeral(
Name(a.opts.Name+".sub"),
Services(svcs...),
Prompt("You are a sub-agent handling a single delegated subtask. "+
"Complete it using the available tools and report the result concisely."),
Provider(a.opts.Provider),
Model(a.opts.Model),
APIKey(a.opts.APIKey),
WithRegistry(a.opts.Registry),
WithClient(a.opts.Client),
WithStore(a.opts.Store),
TraceProvider(a.opts.TraceProvider),
)
// Record lineage so the sub-agent's tool calls carry this run as parent.
sub.parentRunID = a.runID
resp, err := sub.Ask(ctx, task)
if err != nil {
return errResult(call.ID, "sub-agent: "+err.Error())
}
out := map[string]any{"reply": resp.Reply}
b, _ := json.Marshal(out)
return ai.ToolResult{ID: call.ID, Value: out, Content: string(b)}
}
// isAgent reports whether name resolves to a registered agent (a
// service advertising type=agent in its metadata).
func (a *agentImpl) isAgent(name string) bool {
if a.opts.Registry == nil {
return false
}
recs, err := a.opts.Registry.GetService(name)
if err != nil || len(recs) == 0 {
return false
}
if recs[0].Metadata != nil && recs[0].Metadata["type"] == "agent" {
return true
}
for _, n := range recs[0].Nodes {
if n.Metadata != nil && n.Metadata["type"] == "agent" {
return true
}
}
return false
}
// callAgentRPC calls another agent's Agent.Chat endpoint and returns
// its reply.
func (a *agentImpl) callAgentRPC(ctx context.Context, name, msg string) (string, error) {
body, _ := json.Marshal(map[string]string{"message": msg})
req := a.opts.Client.NewRequest(name, "Agent.Chat", &codecBytes.Frame{Data: body})
var rsp codecBytes.Frame
if err := a.opts.Client.Call(ctx, req, &rsp); err != nil {
return "", err
}
var out struct {
Reply string `json:"reply"`
}
if err := json.Unmarshal(rsp.Data, &out); err != nil {
return "", err
}
return out.Reply, nil
}
// planKey is the record key for an agent's plan within its scoped store.
const planKey = "plan"
// loadPlan returns the stored plan as a JSON string, or "" if none.
func (a *agentImpl) loadPlan() string {
recs, err := a.stateStore().Read(planKey)
if err != nil || len(recs) == 0 {
return ""
}
return string(recs[0].Value)
}
func errResult(id, msg string) ai.ToolResult {
m := map[string]string{"error": msg}
b, _ := json.Marshal(m)
return ai.ToolResult{ID: id, Value: m, Content: string(b)}
}
// refused is an error result a guardrail returns, tagged with a structured
// reason (ai.Refused*) so a tool wrapper can react to it without parsing
// the message.
func refused(id, reason, msg string) ai.ToolResult {
r := errResult(id, msg)
r.Refused = reason
return r
}
+167
View File
@@ -0,0 +1,167 @@
package agent
import (
"encoding/json"
"testing"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
)
func TestBuiltinTools(t *testing.T) {
tools := builtinTools()
if len(tools) != 2 {
t.Fatalf("builtinTools() = %d tools, want 2", len(tools))
}
names := map[string]bool{}
for _, tl := range tools {
names[tl.Name] = true
}
if !names[toolPlan] || !names[toolDelegate] {
t.Errorf("builtin tools = %v, want plan and delegate", names)
}
}
func TestHandlePlanPersists(t *testing.T) {
mem := store.NewMemoryStore()
a := New(Name("planner"), WithStore(mem)).(*agentImpl)
steps := map[string]any{
"steps": []any{
map[string]any{"task": "gather requirements", "status": "done"},
map[string]any{"task": "write code", "status": "in_progress"},
},
}
content := a.handlePlan(ai.ToolCall{Name: "plan", Input: steps}).Content
if content == "" {
t.Fatal("handlePlan returned empty content")
}
// The plan must be retrievable from memory.
got := a.loadPlan()
if got == "" {
t.Fatal("loadPlan() returned empty after handlePlan")
}
var decoded map[string]any
if err := json.Unmarshal([]byte(got), &decoded); err != nil {
t.Fatalf("stored plan is not valid JSON: %v", err)
}
if _, ok := decoded["steps"]; !ok {
t.Errorf("stored plan missing steps: %s", got)
}
}
func TestPlanShowsInPrompt(t *testing.T) {
mem := store.NewMemoryStore()
a := New(Name("planner"), Prompt("base prompt"), WithStore(mem)).(*agentImpl)
if got := a.buildPrompt(); got != "base prompt" {
t.Errorf("buildPrompt() with no plan = %q, want %q", got, "base prompt")
}
a.handlePlan(ai.ToolCall{Name: "plan", Input: map[string]any{"steps": []any{map[string]any{"task": "do it", "status": "pending"}}}})
got := a.buildPrompt()
if got == "base prompt" {
t.Error("buildPrompt() should include the plan once one is saved")
}
if !containsStr(got, "do it") {
t.Errorf("buildPrompt() = %q, should contain the saved plan", got)
}
}
func TestDiscoverToolsIncludesBuiltins(t *testing.T) {
reg := registry.NewMemoryRegistry()
a := New(Name("a"), WithRegistry(reg), WithStore(store.NewMemoryStore())).(*agentImpl)
a.setup()
tools, err := a.discoverTools()
if err != nil {
t.Fatalf("discoverTools: %v", err)
}
// No services registered, so the only tools should be the builtins.
if len(tools) != len(builtinTools()) {
t.Fatalf("discoverTools() = %d tools, want %d builtins", len(tools), len(builtinTools()))
}
}
func TestEphemeralAgentHasNoBuiltins(t *testing.T) {
reg := registry.NewMemoryRegistry()
a := New(Name("a.sub"), WithRegistry(reg), WithStore(store.NewMemoryStore())).(*agentImpl)
a.ephemeral = true
a.setup()
tools, err := a.discoverTools()
if err != nil {
t.Fatalf("discoverTools: %v", err)
}
if len(tools) != 0 {
t.Errorf("ephemeral agent discoverTools() = %d tools, want 0", len(tools))
}
}
func TestBuiltinsAccessor(t *testing.T) {
mem := store.NewMemoryStore()
tools, handle := Builtins(
Name("chat"),
WithStore(mem),
WithRegistry(registry.NewMemoryRegistry()),
)
if len(tools) != 2 {
t.Fatalf("Builtins() returned %d tools, want 2", len(tools))
}
// A name that isn't a built-in falls through (ok == false).
if _, _, ok := handle("not_a_builtin", nil); ok {
t.Error("handle(non-builtin) ok = true, want false")
}
// plan is handled and persisted under the configured name.
_, content, ok := handle(toolPlan, map[string]any{
"steps": []any{map[string]any{"task": "x", "status": "pending"}},
})
if !ok {
t.Fatal("handle(plan) ok = false, want true")
}
if content == "" {
t.Fatal("handle(plan) returned empty content")
}
scoped := store.Scope(mem, "agent", "chat")
if recs, err := scoped.Read(planKey); err != nil || len(recs) == 0 {
t.Errorf("plan not persisted in the agent's scoped store: err=%v recs=%d", err, len(recs))
}
}
func TestIsAgent(t *testing.T) {
reg := registry.NewMemoryRegistry()
// A plain service.
if err := reg.Register(&registry.Service{
Name: "task",
Nodes: []*registry.Node{{Id: "task-1", Address: "127.0.0.1:0"}},
}); err != nil {
t.Fatalf("register service: %v", err)
}
// An agent (advertises type=agent).
if err := reg.Register(&registry.Service{
Name: "task-mgr",
Metadata: map[string]string{"type": "agent"},
Nodes: []*registry.Node{{Id: "task-mgr-1", Address: "127.0.0.1:0"}},
}); err != nil {
t.Fatalf("register agent: %v", err)
}
a := New(Name("root"), WithRegistry(reg)).(*agentImpl)
if a.isAgent("task") {
t.Error("isAgent(task) = true, want false (plain service)")
}
if !a.isAgent("task-mgr") {
t.Error("isAgent(task-mgr) = false, want true (agent)")
}
if a.isAgent("nonexistent") {
t.Error("isAgent(nonexistent) = true, want false")
}
}
+92
View File
@@ -0,0 +1,92 @@
package agent
import (
"context"
"strings"
"testing"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
)
// toolContent runs a tool call through a handler and returns the content
// shown to the model — the part these tests assert on.
func toolContent(h ai.ToolHandler, name string, input map[string]any) string {
return h(context.Background(), ai.ToolCall{Name: name, Input: input}).Content
}
// MaxSteps refuses tool calls once the per-Ask limit is exceeded; plan
// is bookkeeping and is never counted.
func TestMaxStepsStopsActions(t *testing.T) {
a := newTestAgent(Name("limited"), MaxSteps(2))
h := a.toolHandler()
// plan must not consume a step.
a.steps = 0
toolContent(h, toolPlan, map[string]any{"steps": []any{}})
if a.steps != 0 {
t.Fatalf("plan consumed a step: steps=%d", a.steps)
}
// First two actions are allowed (they fall through to RPC, which
// fails harmlessly — we only care they weren't refused by the limit).
for i := 1; i <= 2; i++ {
content := toolContent(h, "demo_Svc_Do", map[string]any{})
if strings.Contains(content, "step limit") {
t.Fatalf("action %d wrongly hit the step limit", i)
}
}
// Third action exceeds MaxSteps(2) and must be refused.
content := toolContent(h, "demo_Svc_Do", map[string]any{})
if !strings.Contains(content, "step limit") {
t.Errorf("third action should hit the step limit; got %q", content)
}
}
// ApproveTool blocks an action when the hook denies it, and the denial
// reason is surfaced to the model.
func TestApproveToolBlocks(t *testing.T) {
var sawTool string
a := newTestAgent(Name("gated"),
ApproveTool(func(tool string, input map[string]any) (bool, string) {
sawTool = tool
return false, "needs sign-off"
}),
)
content := toolContent(a.toolHandler(), "demo_Svc_Do", map[string]any{})
if sawTool != "demo_Svc_Do" {
t.Errorf("approver saw %q, want demo_Svc_Do", sawTool)
}
if !strings.Contains(content, "not approved") || !strings.Contains(content, "needs sign-off") {
t.Errorf("blocked call should surface the reason; got %q", content)
}
}
// A denying approver must not gate the internal plan tool.
func TestApproveToolDoesNotGatePlan(t *testing.T) {
mem := store.NewMemoryStore()
a := New(
Name("gated"),
Provider("fake"),
WithRegistry(registry.NewMemoryRegistry()),
WithStore(mem),
ApproveTool(func(tool string, input map[string]any) (bool, string) {
return false, "deny everything"
}),
).(*agentImpl)
a.setup()
content := toolContent(a.toolHandler(), toolPlan, map[string]any{
"steps": []any{map[string]any{"task": "x", "status": "pending"}},
})
if strings.Contains(content, "not approved") {
t.Errorf("plan must not be gated by ApproveTool; got %q", content)
}
if recs, _ := store.Scope(mem, "agent", "gated").Read(planKey); len(recs) == 0 {
t.Error("plan should have been persisted despite the denying approver")
}
}
+181
View File
@@ -0,0 +1,181 @@
package agent
import (
"context"
"strings"
"testing"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/client"
codecBytes "go-micro.dev/v6/codec/bytes"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
)
// fakeGen drives the fake provider's Generate. Tests set it and reset
// it with a deferred cleanup. Tests in this package are not parallel,
// so a package-level hook is safe.
var fakeGen func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error)
type fakeModel struct{ opts ai.Options }
func (m *fakeModel) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&m.opts)
}
return nil
}
func (m *fakeModel) Options() ai.Options { return m.opts }
func (m *fakeModel) Generate(ctx context.Context, req *ai.Request, _ ...ai.GenerateOption) (*ai.Response, error) {
if fakeGen != nil {
return fakeGen(ctx, m.opts, req)
}
return &ai.Response{Reply: "ok"}, nil
}
func (m *fakeModel) Stream(ctx context.Context, req *ai.Request, _ ...ai.GenerateOption) (ai.Stream, error) {
return nil, nil
}
func (m *fakeModel) String() string { return "fake" }
func init() {
ai.Register("fake", func(opts ...ai.Option) ai.Model {
m := &fakeModel{}
_ = m.Init(opts...)
return m
})
}
// fakeClient embeds the default client (so NewRequest works) and
// overrides Call with a test-supplied function.
type fakeClient struct {
client.Client
callFn func(ctx context.Context, req client.Request, rsp interface{}) error
}
func (c *fakeClient) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
return c.callFn(ctx, req, rsp)
}
func newTestAgent(opts ...Option) *agentImpl {
base := []Option{
Provider("fake"),
WithRegistry(registry.NewMemoryRegistry()),
WithStore(store.NewMemoryStore()),
}
a := New(append(base, opts...)...).(*agentImpl)
a.setup()
return a
}
// The model is offered the plan and delegate tools, and calling the
// plan tool persists the plan to memory.
func TestAskExposesAndRunsPlan(t *testing.T) {
var sawPlan, sawDelegate bool
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
for _, tl := range req.Tools {
switch tl.Name {
case toolPlan:
sawPlan = true
case toolDelegate:
sawDelegate = true
}
}
// Simulate the model recording a plan.
if opts.ToolHandler != nil {
opts.ToolHandler(context.Background(), ai.ToolCall{
Name: toolPlan,
Input: map[string]any{
"steps": []any{map[string]any{"task": "step one", "status": "pending"}},
},
})
}
return &ai.Response{Answer: "done"}, nil
}
defer func() { fakeGen = nil }()
a := newTestAgent(Name("worker"))
resp, err := a.Ask(context.Background(), "do some multi-step work")
if err != nil {
t.Fatalf("Ask: %v", err)
}
if !sawPlan || !sawDelegate {
t.Errorf("model should be offered plan and delegate tools: plan=%v delegate=%v", sawPlan, sawDelegate)
}
if resp.Reply == "" {
t.Error("Ask returned empty reply")
}
if plan := a.loadPlan(); !strings.Contains(plan, "step one") {
t.Errorf("plan tool result not persisted; loadPlan() = %q", plan)
}
}
// Delegating with no matching agent creates an ephemeral sub-agent with
// a fresh, isolated context (no builtin tools) and returns its reply.
func TestDelegateEphemeral(t *testing.T) {
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
if strings.Contains(req.SystemPrompt, "sub-agent") {
for _, tl := range req.Tools {
if tl.Name == toolPlan || tl.Name == toolDelegate {
t.Errorf("ephemeral sub-agent must not have builtin tool %q", tl.Name)
}
}
return &ai.Response{Reply: "subtask complete"}, nil
}
return &ai.Response{Reply: "parent"}, nil
}
defer func() { fakeGen = nil }()
a := newTestAgent(Name("root"))
content := a.handleDelegate(context.Background(), ai.ToolCall{Name: "delegate", Input: map[string]any{"task": "summarize the report"}}).Content
if !strings.Contains(content, "subtask complete") {
t.Errorf("delegate should return the sub-agent's reply; got %q", content)
}
}
// Delegating to a name that resolves to a registered agent goes over
// RPC to that agent rather than spawning a sub-agent.
func TestDelegateToRegisteredAgent(t *testing.T) {
reg := registry.NewMemoryRegistry()
if err := reg.Register(&registry.Service{
Name: "comms",
Metadata: map[string]string{"type": "agent"},
Nodes: []*registry.Node{{Id: "comms-1", Address: "127.0.0.1:0"}},
}); err != nil {
t.Fatalf("register agent: %v", err)
}
var calledService, calledEndpoint string
fc := &fakeClient{Client: client.DefaultClient}
fc.callFn = func(ctx context.Context, req client.Request, rsp interface{}) error {
calledService, calledEndpoint = req.Service(), req.Endpoint()
frame := rsp.(*codecBytes.Frame)
frame.Data = []byte(`{"reply":"notified alice","agent":"comms"}`)
return nil
}
// fakeGen guards against the ephemeral path being taken by mistake.
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
t.Error("delegate to a registered agent must not spawn a sub-agent")
return &ai.Response{}, nil
}
defer func() { fakeGen = nil }()
a := newTestAgent(Name("root"), WithRegistry(reg), WithClient(fc))
content := a.handleDelegate(context.Background(), ai.ToolCall{Name: "delegate", Input: map[string]any{"task": "notify alice", "to": "comms"}}).Content
if calledService != "comms" || calledEndpoint != "Agent.Chat" {
t.Errorf("expected RPC to comms Agent.Chat, got %s %s", calledService, calledEndpoint)
}
if !strings.Contains(content, "notified alice") {
t.Errorf("delegate-first result missing agent reply; got %q", content)
}
}
// Delegate requires a task.
func TestDelegateRequiresTask(t *testing.T) {
a := newTestAgent(Name("root"))
content := a.handleDelegate(context.Background(), ai.ToolCall{Name: "delegate", Input: map[string]any{}}).Content
if !strings.Contains(content, "error") {
t.Errorf("delegate with no task should error; got %q", content)
}
}
+71
View File
@@ -0,0 +1,71 @@
package agent
import (
"strings"
"testing"
)
// Repeating the same tool call with the same arguments is refused once it
// exceeds LoopLimit, and the model is told to change approach.
func TestLoopDetectionStopsRepeats(t *testing.T) {
a := newTestAgent(Name("looper"), LoopLimit(3))
h := a.toolHandler()
// First 3 identical calls are allowed (they fall through to RPC,
// which fails harmlessly — we only care they weren't refused as loops).
for i := 1; i <= 3; i++ {
content := toolContent(h, "demo_Svc_Do", map[string]any{"q": "x"})
if strings.Contains(content, "loop detected") {
t.Fatalf("call %d wrongly flagged as a loop", i)
}
}
// The 4th identical call is refused as a loop.
content := toolContent(h, "demo_Svc_Do", map[string]any{"q": "x"})
if !strings.Contains(content, "loop detected") {
t.Errorf("4th identical call should be refused as a loop; got %q", content)
}
}
// Different arguments are not a loop, even past the limit.
func TestLoopDetectionAllowsDistinctCalls(t *testing.T) {
a := newTestAgent(Name("distinct"), LoopLimit(2))
h := a.toolHandler()
for i := 0; i < 5; i++ {
content := toolContent(h, "demo_Svc_Do", map[string]any{"q": i}) // distinct args each time
if strings.Contains(content, "loop detected") {
t.Fatalf("distinct call %d wrongly flagged as a loop", i)
}
}
}
// LoopLimit(0) disables detection.
func TestLoopDetectionDisabled(t *testing.T) {
a := newTestAgent(Name("noloop"), LoopLimit(0))
h := a.toolHandler()
for i := 0; i < 6; i++ {
content := toolContent(h, "demo_Svc_Do", map[string]any{"q": "same"})
if strings.Contains(content, "loop detected") {
t.Fatalf("loop detection should be disabled with LoopLimit(0)")
}
}
}
// It defaults on (lenient) so repeated identical calls are caught without
// any configuration.
func TestLoopDetectionDefaultOn(t *testing.T) {
a := New(Name("d"), Provider("fake")).(*agentImpl)
a.setup()
if a.opts.LoopLimit <= 0 {
t.Fatalf("LoopLimit should default on, got %d", a.opts.LoopLimit)
}
h := a.toolHandler()
var lastContent string
for i := 0; i < a.opts.LoopLimit+1; i++ {
lastContent = toolContent(h, "demo_Svc_Do", map[string]any{})
}
if !strings.Contains(lastContent, "loop detected") {
t.Errorf("default loop detection should catch repeated calls; got %q", lastContent)
}
}
+98
View File
@@ -0,0 +1,98 @@
package agent
import (
"encoding/json"
"sync"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/store"
)
// Memory is an agent's conversation memory. Like the rest of the
// framework it is pluggable: the default is store-backed and durable
// across restarts, but any implementation can be supplied with
// WithMemory — in-process, a database, or a semantic/vector store.
type Memory interface {
// Add appends a message to the conversation.
Add(role, content string)
// Messages returns the retained conversation, oldest first.
Messages() []ai.Message
// Clear resets the conversation.
Clear()
}
// NewMemory returns the default store-backed memory: an in-process
// conversation buffer (truncated to limit) that persists to the store
// under key, so an agent picks up where it left off after a restart.
// A nil store or empty key yields non-persistent memory.
func NewMemory(s store.Store, key string, limit int) Memory {
m := &storeMemory{store: s, key: key, hist: ai.NewHistory(limit)}
m.load()
return m
}
// NewInMemory returns conversation memory that is not persisted.
func NewInMemory(limit int) Memory {
return &storeMemory{hist: ai.NewHistory(limit)}
}
// storeMemory is the default Memory: an ai.History buffer optionally
// persisted to a store.
type storeMemory struct {
mu sync.Mutex
store store.Store
key string
hist *ai.History
}
func (m *storeMemory) Add(role, content string) {
m.mu.Lock()
m.hist.Add(role, content)
m.mu.Unlock()
m.save()
}
func (m *storeMemory) Messages() []ai.Message {
m.mu.Lock()
defer m.mu.Unlock()
return m.hist.Messages()
}
func (m *storeMemory) Clear() {
m.mu.Lock()
m.hist.Reset()
m.mu.Unlock()
m.save()
}
func (m *storeMemory) load() {
if m.store == nil || m.key == "" {
return
}
recs, err := m.store.Read(m.key)
if err != nil || len(recs) == 0 {
return
}
var msgs []ai.Message
if err := json.Unmarshal(recs[0].Value, &msgs); err != nil {
return
}
m.mu.Lock()
for _, msg := range msgs {
m.hist.Add(msg.Role, msg.Content)
}
m.mu.Unlock()
}
func (m *storeMemory) save() {
if m.store == nil || m.key == "" {
return
}
m.mu.Lock()
data, err := json.Marshal(m.hist.Messages())
m.mu.Unlock()
if err != nil {
return
}
_ = m.store.Write(&store.Record{Key: m.key, Value: data})
}
+114
View File
@@ -0,0 +1,114 @@
package agent
import (
"context"
"errors"
"strings"
"testing"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
)
func TestStoreMemoryPersists(t *testing.T) {
st := store.NewMemoryStore()
m := NewMemory(st, "agent/x/history", 10)
m.Add("user", "hello")
m.Add("assistant", "hi there")
// A fresh memory over the same store/key restores the conversation.
reloaded := NewMemory(st, "agent/x/history", 10)
if got := len(reloaded.Messages()); got != 2 {
t.Fatalf("restored %d messages, want 2", got)
}
}
func TestInMemoryNotPersisted(t *testing.T) {
m := NewInMemory(10)
m.Add("user", "x")
if got := len(m.Messages()); got != 1 {
t.Fatalf("got %d messages, want 1", got)
}
if got := len(NewInMemory(10).Messages()); got != 0 {
t.Errorf("a separate in-memory should be empty, got %d", got)
}
}
func TestMemoryClearPersists(t *testing.T) {
st := store.NewMemoryStore()
m := NewMemory(st, "agent/y/history", 10)
m.Add("user", "x")
m.Clear()
if got := len(m.Messages()); got != 0 {
t.Errorf("after Clear got %d messages, want 0", got)
}
if got := len(NewMemory(st, "agent/y/history", 10).Messages()); got != 0 {
t.Errorf("cleared state should persist, reload got %d", got)
}
}
func TestWithMemoryUsed(t *testing.T) {
custom := NewInMemory(5)
a := New(
Name("z"),
Provider("fake"),
WithRegistry(registry.NewMemoryRegistry()),
WithStore(store.NewMemoryStore()),
WithMemory(custom),
).(*agentImpl)
a.setup()
if a.mem != custom {
t.Error("WithMemory should make the agent use the supplied memory")
}
}
// A custom tool is offered to the model and dispatched to its handler.
func TestWithToolExposedAndDispatched(t *testing.T) {
var got map[string]any
a := newTestAgent(Name("calc-agent"),
WithTool("calc", "adds two numbers",
map[string]any{
"a": map[string]any{"type": "number"},
"b": map[string]any{"type": "number"},
},
func(ctx context.Context, input map[string]any) (string, error) {
got = input
return `{"sum":3}`, nil
}))
tools, err := a.discoverTools()
if err != nil {
t.Fatalf("discoverTools: %v", err)
}
found := false
for _, tl := range tools {
if tl.Name == "calc" {
found = true
}
}
if !found {
t.Fatal("custom tool 'calc' was not offered to the model")
}
content := toolContent(a.toolHandler(), "calc", map[string]any{"a": 1.0, "b": 2.0})
if got == nil {
t.Fatal("custom tool handler was not called")
}
if !strings.Contains(content, "sum") {
t.Errorf("custom tool result not returned: %q", content)
}
}
// A custom tool returning an error surfaces it to the model.
func TestWithToolError(t *testing.T) {
a := newTestAgent(Name("err-agent"),
WithTool("boom", "always fails", nil,
func(ctx context.Context, input map[string]any) (string, error) {
return "", errors.New("kaboom")
}))
content := toolContent(a.toolHandler(), "boom", nil)
if !strings.Contains(content, "kaboom") {
t.Errorf("tool error not surfaced: %q", content)
}
}
+249
View File
@@ -0,0 +1,249 @@
package agent
import (
"context"
"time"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/client"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
"go.opentelemetry.io/otel/trace"
)
// Option configures an Agent.
type Option func(*Options)
// ApproveFunc decides whether an agent may execute a tool call before it
// runs. Returning false blocks the call; the reason is shown to the
// model so it can adapt. Use it for human-in-the-loop approval or policy
// checks. It is called for actions (service tools and delegate), not for
// the internal plan tool.
type ApproveFunc func(tool string, input map[string]any) (approved bool, reason string)
// ToolFunc handles a custom tool call. Return the result as a string
// (often JSON); return an error to report failure back to the model.
type ToolFunc func(ctx context.Context, input map[string]any) (string, error)
// customTool is a developer-registered tool beyond the agent's services.
type customTool struct {
def ai.Tool
handler ToolFunc
}
// Options holds agent configuration.
type Options struct {
Name string
Services []string
Prompt string
Provider string
Model string
APIKey string
Registry registry.Registry
Client client.Client
Store store.Store
HistoryLimit int
// ModelTimeout bounds each provider Generate call (0 disables).
ModelTimeout time.Duration
// ModelMaxAttempts bounds provider Generate attempts including the first
// call. Default 1 — retries are opt-in (enable with ModelRetry). A Generate
// runs the whole tool-execution turn, so auto-retrying it would re-run
// already-executed, possibly side-effecting tool calls; keep it explicit.
ModelMaxAttempts int
// ModelRetryBackoff is the base delay between transient provider failures
// (grows exponentially per attempt when retries are enabled).
ModelRetryBackoff time.Duration
// Memory is the agent's conversation memory. Nil = the default
// store-backed memory (durable across restarts).
Memory Memory
// MaxSteps bounds the number of tool executions per Ask (0 =
// unbounded). Once exceeded, further tool calls are refused and the
// model is told to stop and summarize. A stopping condition.
MaxSteps int
// LoopLimit bounds how many times the agent may call the same tool
// with the same arguments in one Ask before the call is refused as a
// no-progress loop (0 = disabled). Catches the agent repeating an
// identical action — which MaxSteps only bounds by total count.
LoopLimit int
// Approve gates each action before it runs. Nil = allow all.
Approve ApproveFunc
// A2AAddress, if set, makes Run serve this agent over the A2A protocol
// on that address directly (no separate gateway), e.g. ":4000".
A2AAddress string
// TraceProvider enables OpenTelemetry spans for agent runs, model calls,
// and tool calls. Nil disables instrumentation.
TraceProvider trace.TracerProvider
// tools are developer-registered custom tools (see WithTool).
tools []customTool
// wrappers are developer-registered tool-execution wrappers
// (see WrapTool), applied outside the built-in guardrails.
wrappers []ai.ToolWrapper
}
func newOptions(opts ...Option) Options {
o := Options{
Registry: registry.DefaultRegistry,
Client: client.DefaultClient,
Store: store.DefaultStore,
HistoryLimit: 50,
ModelTimeout: 30 * time.Second,
ModelMaxAttempts: 1, // retries opt-in via ModelRetry (see field doc)
ModelRetryBackoff: 100 * time.Millisecond,
// On by default and lenient: identical repeated calls are a
// no-progress loop, never useful. Set LoopLimit(0) to disable.
LoopLimit: 3,
}
for _, opt := range opts {
opt(&o)
}
return o
}
// Name sets the agent name.
func Name(n string) Option {
return func(o *Options) { o.Name = n }
}
// Services sets which services this agent manages.
func Services(names ...string) Option {
return func(o *Options) { o.Services = names }
}
// Prompt sets the system prompt.
func Prompt(p string) Option {
return func(o *Options) { o.Prompt = p }
}
// Provider sets the LLM provider.
func Provider(p string) Option {
return func(o *Options) { o.Provider = p }
}
// Model sets the LLM model name.
func Model(m string) Option {
return func(o *Options) { o.Model = m }
}
// APIKey sets the API key for the LLM provider.
func APIKey(k string) Option {
return func(o *Options) { o.APIKey = k }
}
// WithRegistry sets the service registry.
func WithRegistry(r registry.Registry) Option {
return func(o *Options) { o.Registry = r }
}
// WithClient sets the RPC client.
func WithClient(c client.Client) Option {
return func(o *Options) { o.Client = c }
}
// WithStore sets the store for agent memory.
func WithStore(s store.Store) Option {
return func(o *Options) { o.Store = s }
}
// HistoryLimit sets the max conversation messages to retain.
func HistoryLimit(n int) Option {
return func(o *Options) { o.HistoryLimit = n }
}
// MaxSteps bounds tool executions per Ask (0 = unbounded). A stopping
// condition: beyond the limit, tool calls are refused and the model is
// told to stop and summarize.
func MaxSteps(n int) Option {
return func(o *Options) { o.MaxSteps = n }
}
// ApproveTool sets a human-in-the-loop / policy hook called before each
// action (service tools and delegate). Returning false blocks the call.
func ApproveTool(fn ApproveFunc) Option {
return func(o *Options) { o.Approve = fn }
}
// LoopLimit sets how many times the agent may repeat the same tool call
// (same name and arguments) in one Ask before it is refused as a
// no-progress loop. 0 disables loop detection.
func LoopLimit(n int) Option {
return func(o *Options) { o.LoopLimit = n }
}
// ModelCallTimeout sets the timeout for each provider Generate call.
func ModelCallTimeout(d time.Duration) Option {
return func(o *Options) { o.ModelTimeout = d }
}
// ModelRetry sets the provider retry budget and backoff for transient failures.
func ModelRetry(maxAttempts int, backoff time.Duration) Option {
return func(o *Options) {
o.ModelMaxAttempts = maxAttempts
o.ModelRetryBackoff = backoff
}
}
// WithA2A makes Run serve the agent over the A2A protocol on addr (e.g.
// ":4000"), so other agents can reach it directly by URL without a
// separate gateway. The agent stays a normal go-micro service as well;
// this adds a second, A2A-native HTTP endpoint that calls it in-process.
func WithA2A(addr string) Option {
return func(o *Options) { o.A2AAddress = addr }
}
// WithMemory sets the agent's conversation memory. The default is
// store-backed memory keyed by agent name; supply your own to use an
// in-process, database, or semantic store.
func WithMemory(m Memory) Option {
return func(o *Options) { o.Memory = m }
}
// WrapTool registers a tool-execution wrapper, the tool-side analog of
// a client/server middleware wrapper. Each wrapper takes the next handler
// and returns a new one; code before the next(...) call runs before the
// tool executes, code after runs after. Use it for logging, metrics,
// retries, or custom policy. Wrappers run outside the built-in guardrails
// (MaxSteps, LoopLimit, ApproveTool), so they observe every call and its
// result, including refusals. Multiple wrappers compose outermost-first.
//
// micro.NewAgent("worker", micro.AgentWrapTool(
// func(next ai.ToolHandler) ai.ToolHandler {
// return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
// res := next(ctx, call)
// log.Printf("id=%s tool=%s", call.ID, call.Name)
// return res
// }
// }))
func WrapTool(w ...ai.ToolWrapper) Option {
return func(o *Options) {
o.wrappers = append(o.wrappers, w...)
}
}
// WithTool registers a custom tool the agent can call, beyond the
// services it discovers — a local function, an external API, anything.
// properties is the JSON-schema map for the tool's parameters.
func WithTool(name, description string, properties map[string]any, handler ToolFunc) Option {
return func(o *Options) {
o.tools = append(o.tools, customTool{
def: ai.Tool{
Name: name,
OriginalName: name,
Description: description,
Properties: properties,
},
handler: handler,
})
}
}
// TraceProvider enables OpenTelemetry tracing for agent runs. When nil,
// agent tracing and run timeline recording are disabled.
func TraceProvider(tp trace.TracerProvider) Option {
return func(o *Options) { o.TraceProvider = tp }
}
+295
View File
@@ -0,0 +1,295 @@
package agent
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/store"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
const agentInstrumentationName = "go-micro.dev/v6/agent"
const (
spanNameRun = "agent.run"
spanNameModelCall = "agent.model.call"
spanNameToolCall = "agent.tool.call"
AttrRunID = "agent.run.id"
AttrParentRunID = "agent.run.parent_id"
AttrAgentName = "agent.name"
AttrProvider = "agent.model.provider"
AttrModel = "agent.model.name"
AttrLatencyMS = "agent.latency_ms"
AttrInputTokens = "agent.tokens.input"
AttrOutputTokens = "agent.tokens.output"
AttrTotalTokens = "agent.tokens.total"
AttrToolName = "agent.tool.name"
AttrDelegate = "agent.delegate"
AttrGuardrailBlock = "agent.guardrail.block"
AttrRefusal = "agent.refusal"
)
type RunEvent struct {
Time time.Time `json:"time"`
RunID string `json:"run_id"`
ParentID string `json:"parent_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
Agent string `json:"agent"`
Kind string `json:"kind"`
Name string `json:"name,omitempty"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
LatencyMS int64 `json:"latency_ms,omitempty"`
Tokens Usage `json:"tokens,omitempty"`
Refused string `json:"refused,omitempty"`
Error string `json:"error,omitempty"`
}
type Usage = ai.Usage
// RunSummary is a compact index entry for a recorded agent run.
type RunSummary struct {
RunID string `json:"run_id"`
Agent string `json:"agent"`
ParentID string `json:"parent_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
StartedAt time.Time `json:"started_at"`
UpdatedAt time.Time `json:"updated_at"`
Events int `json:"events"`
LastKind string `json:"last_kind,omitempty"`
LastError string `json:"last_error,omitempty"`
}
func (a *agentImpl) tracer() trace.Tracer {
return a.opts.TraceProvider.Tracer(agentInstrumentationName)
}
func (a *agentImpl) startRun(ctx context.Context, message string) (context.Context, func(error)) {
if a.opts.TraceProvider == nil {
return ctx, func(error) {}
}
info, _ := ai.RunInfoFrom(ctx)
ctx, span := a.tracer().Start(ctx, spanNameRun, trace.WithSpanKind(trace.SpanKindInternal), trace.WithAttributes(
attribute.String(AttrRunID, info.RunID), attribute.String(AttrParentRunID, info.ParentID), attribute.String(AttrAgentName, info.Agent)))
start := time.Now()
a.recordSpanEvent(span, RunEvent{Time: start, RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "run", Name: message})
return ctx, func(err error) {
latency := time.Since(start).Milliseconds()
span.SetAttributes(attribute.Int64(AttrLatencyMS, latency))
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
a.recordSpanEvent(span, RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "error", LatencyMS: latency, Error: err.Error()})
} else {
span.SetStatus(codes.Ok, "")
a.recordSpanEvent(span, RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "done", LatencyMS: latency})
}
span.End()
}
}
type tracedModel struct {
ai.Model
a *agentImpl
}
func (a *agentImpl) tracedModel(m ai.Model) ai.Model { return &tracedModel{Model: m, a: a} }
func (m *tracedModel) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
if m.a.opts.TraceProvider == nil {
return m.Model.Generate(ctx, req, opts...)
}
info, _ := ai.RunInfoFrom(ctx)
provider := m.String()
model := m.Options().Model
ctx, span := m.a.tracer().Start(ctx, spanNameModelCall, trace.WithAttributes(attribute.String(AttrProvider, provider), attribute.String(AttrModel, model)))
start := time.Now()
resp, err := m.Model.Generate(ctx, req, opts...)
dur := time.Since(start).Milliseconds()
attrs := []attribute.KeyValue{attribute.Int64(AttrLatencyMS, dur)}
usage := ai.Usage{}
if resp != nil {
usage = resp.Usage
attrs = appendUsage(attrs, usage)
}
span.SetAttributes(attrs...)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
e := RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "model", Provider: provider, Model: model, LatencyMS: dur, Tokens: usage}
if err != nil {
e.Error = err.Error()
}
m.a.recordSpanEvent(span, e)
return resp, err
}
func appendUsage(attrs []attribute.KeyValue, u ai.Usage) []attribute.KeyValue {
if u.InputTokens > 0 {
attrs = append(attrs, attribute.Int(AttrInputTokens, u.InputTokens))
}
if u.OutputTokens > 0 {
attrs = append(attrs, attribute.Int(AttrOutputTokens, u.OutputTokens))
}
if u.TotalTokens > 0 {
attrs = append(attrs, attribute.Int(AttrTotalTokens, u.TotalTokens))
}
return attrs
}
func (a *agentImpl) traceTool(next ai.ToolHandler) ai.ToolHandler {
if a.opts.TraceProvider == nil {
return next
}
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
info, _ := ai.RunInfoFrom(ctx)
ctx, span := a.tracer().Start(ctx, spanNameToolCall, trace.WithAttributes(attribute.String(AttrToolName, call.Name), attribute.Bool(AttrDelegate, call.Name == toolDelegate)))
start := time.Now()
res := next(ctx, call)
dur := time.Since(start).Milliseconds()
attrs := []attribute.KeyValue{attribute.Int64(AttrLatencyMS, dur)}
if res.Refused != "" {
attrs = append(attrs, attribute.Bool(AttrGuardrailBlock, true), attribute.String(AttrRefusal, res.Refused))
}
span.SetAttributes(attrs...)
resErr := resultError(res)
if res.Refused != "" {
span.SetStatus(codes.Error, res.Refused)
} else if resErr != "" {
span.SetStatus(codes.Error, resErr)
} else {
span.SetStatus(codes.Ok, "")
}
span.End()
a.recordSpanEvent(span, RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "tool", Name: call.Name, LatencyMS: dur, Refused: res.Refused, Error: resErr})
return res
}
}
func resultError(res ai.ToolResult) string {
if m, ok := res.Value.(map[string]string); ok {
return m["error"]
}
if m, ok := res.Value.(map[string]any); ok {
if err, _ := m["error"].(string); err != "" {
return err
}
}
return ""
}
func (a *agentImpl) recordSpanEvent(span trace.Span, e RunEvent) {
if sc := span.SpanContext(); sc.IsValid() {
e.TraceID = sc.TraceID().String()
e.SpanID = sc.SpanID().String()
}
a.recordRunEvent(e)
}
func (a *agentImpl) recordRunEvent(e RunEvent) {
if a.opts.TraceProvider == nil || e.RunID == "" {
return
}
b, _ := json.Marshal(e)
key := fmt.Sprintf("runs/%s/%020d-%s", e.RunID, e.Time.UnixNano(), e.Kind)
_ = a.stateStore().Write(&store.Record{Key: key, Value: b})
}
// ListRunSummaries returns a deterministic summary of recorded runs for agentName.
func ListRunSummaries(s store.Store, agentName string) ([]RunSummary, error) {
st := store.Scope(s, "agent", agentName)
keys, err := st.List(store.ListPrefix("runs/"))
if err != nil {
return nil, err
}
runs := map[string]bool{}
for _, k := range keys {
parts := strings.Split(k, "/")
if len(parts) >= 2 && parts[1] != "" {
runs[parts[1]] = true
}
}
ids := make([]string, 0, len(runs))
for id := range runs {
ids = append(ids, id)
}
sort.Strings(ids)
summaries := make([]RunSummary, 0, len(ids))
for _, id := range ids {
events, err := LoadRunEvents(s, agentName, id)
if err != nil {
return nil, err
}
if len(events) == 0 {
continue
}
first := events[0]
last := events[len(events)-1]
summary := RunSummary{
RunID: id,
Agent: first.Agent,
ParentID: first.ParentID,
TraceID: first.TraceID,
SpanID: first.SpanID,
StartedAt: first.Time,
UpdatedAt: last.Time,
Events: len(events),
LastKind: last.Kind,
LastError: last.Error,
}
for _, e := range events {
if e.Agent != "" {
summary.Agent = e.Agent
}
if e.ParentID != "" {
summary.ParentID = e.ParentID
}
if e.TraceID != "" {
summary.TraceID = e.TraceID
}
if e.SpanID != "" {
summary.SpanID = e.SpanID
}
if e.Error != "" {
summary.LastError = e.Error
}
}
summaries = append(summaries, summary)
}
return summaries, nil
}
func LoadRunEvents(s store.Store, agentName, runID string) ([]RunEvent, error) {
st := store.Scope(s, "agent", agentName)
keys, err := st.List(store.ListPrefix("runs/" + runID + "/"))
if err != nil {
return nil, err
}
sort.Strings(keys)
events := make([]RunEvent, 0, len(keys))
for _, k := range keys {
recs, err := st.Read(k)
if err != nil || len(recs) == 0 {
continue
}
var e RunEvent
if json.Unmarshal(recs[0].Value, &e) == nil {
events = append(events, e)
}
}
return events, nil
}
+173
View File
@@ -0,0 +1,173 @@
package agent
import (
"context"
"encoding/json"
"testing"
"time"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/store"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)
type otelTestModel struct{ opts ai.Options }
func (m *otelTestModel) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&m.opts)
}
return nil
}
func (m *otelTestModel) Options() ai.Options { return m.opts }
func (m *otelTestModel) String() string { return "oteltest" }
func (m *otelTestModel) Stream(context.Context, *ai.Request, ...ai.GenerateOption) (ai.Stream, error) {
return nil, nil
}
func (m *otelTestModel) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
if m.opts.ToolHandler != nil {
_ = m.opts.ToolHandler(ctx, ai.ToolCall{ID: "call-1", Name: "probe", Input: map[string]any{"ok": true}})
}
return &ai.Response{Reply: "done", Usage: ai.Usage{InputTokens: 2, OutputTokens: 3, TotalTokens: 5}}, nil
}
func init() {
ai.Register("oteltest", func(opts ...ai.Option) ai.Model { return &otelTestModel{opts: ai.NewOptions(opts...)} })
}
func TestAgentOpenTelemetrySpans(t *testing.T) {
exp := tracetest.NewInMemoryExporter()
tp := trace.NewTracerProvider(trace.WithSyncer(exp))
st := store.NewMemoryStore()
a := New(Name("runner"), Provider("oteltest"), Model("unit-model"), WithStore(st), TraceProvider(tp), WithTool("probe", "probe", nil, func(context.Context, map[string]any) (string, error) { return "ok", nil }))
if _, err := a.Ask(context.Background(), "hello"); err != nil {
t.Fatal(err)
}
spans := exp.GetSpans().Snapshots()
want := map[string]bool{spanNameRun: false, spanNameModelCall: false, spanNameToolCall: false}
for _, s := range spans {
if _, ok := want[s.Name()]; ok {
want[s.Name()] = true
}
}
for name, seen := range want {
if !seen {
t.Fatalf("span %s not emitted; got %d spans", name, len(spans))
}
}
keys, err := store.Scope(st, "agent", "runner").List(store.ListPrefix("runs/"))
if err != nil {
t.Fatal(err)
}
if len(keys) == 0 {
t.Fatal("expected run events to be recorded")
}
summaries, err := ListRunSummaries(st, "runner")
if err != nil {
t.Fatal(err)
}
if len(summaries) != 1 {
t.Fatalf("got %d summaries, want 1", len(summaries))
}
if summaries[0].LastKind != "done" {
t.Fatalf("LastKind = %q, want done", summaries[0].LastKind)
}
if summaries[0].TraceID == "" || summaries[0].SpanID == "" {
t.Fatalf("summary missing trace correlation: %#v", summaries[0])
}
events, err := LoadRunEvents(st, "runner", summaries[0].RunID)
if err != nil {
t.Fatal(err)
}
if len(events) == 0 || events[0].TraceID == "" || events[0].SpanID == "" {
t.Fatalf("events missing trace correlation: %#v", events)
}
}
func TestAgentOpenTelemetryNoopWhenUnconfigured(t *testing.T) {
st := store.NewMemoryStore()
a := New(Name("runner-noop"), Provider("oteltest"), WithStore(st), WithTool("probe", "probe", nil, func(context.Context, map[string]any) (string, error) { return "ok", nil }))
if _, err := a.Ask(context.Background(), "hello"); err != nil {
t.Fatal(err)
}
keys, err := store.Scope(st, "agent", "runner-noop").List(store.ListPrefix("runs/"))
if err != nil {
t.Fatal(err)
}
if len(keys) != 0 {
t.Fatalf("expected no run timeline without TraceProvider, got %v", keys)
}
if _, ok := a.(*agentImpl).model.(*tracedModel); ok {
t.Fatal("model should not be wrapped when TraceProvider is nil")
}
}
func TestLoadRunEventsSortsTimelineKeys(t *testing.T) {
st := store.NewMemoryStore()
scoped := store.Scope(st, "agent", "runner")
runID := "run-1"
events := []RunEvent{
{Time: time.Unix(0, 3), RunID: runID, Agent: "runner", Kind: "tool", Name: "third"},
{Time: time.Unix(0, 1), RunID: runID, Agent: "runner", Kind: "run", Name: "first"},
{Time: time.Unix(0, 2), RunID: runID, Agent: "runner", Kind: "model", Name: "second"},
}
for _, e := range events {
b, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
key := "runs/" + runID + "/" + e.Time.Format("20060102150405.000000000") + "-" + e.Kind
if err := scoped.Write(&store.Record{Key: key, Value: b}); err != nil {
t.Fatal(err)
}
}
got, err := LoadRunEvents(st, "runner", runID)
if err != nil {
t.Fatal(err)
}
if len(got) != 3 {
t.Fatalf("got %d events, want 3", len(got))
}
for i, want := range []string{"first", "second", "third"} {
if got[i].Name != want {
t.Fatalf("event %d = %q, want %q (timeline: %#v)", i, got[i].Name, want, got)
}
}
}
func TestListRunSummaries(t *testing.T) {
st := store.NewMemoryStore()
scoped := store.Scope(st, "agent", "runner")
events := []RunEvent{
{Time: time.Unix(0, 1), RunID: "run-a", Agent: "runner", TraceID: "trace-a", SpanID: "span-a", Kind: "run", Name: "first"},
{Time: time.Unix(0, 2), RunID: "run-a", Agent: "runner", Kind: "tool", Name: "probe"},
{Time: time.Unix(0, 3), RunID: "run-b", Agent: "runner", ParentID: "parent", Kind: "run", Name: "second"},
{Time: time.Unix(0, 4), RunID: "run-b", Agent: "runner", ParentID: "parent", Kind: "error", Error: "boom"},
}
for _, e := range events {
b, err := json.Marshal(e)
if err != nil {
t.Fatal(err)
}
key := "runs/" + e.RunID + "/" + e.Time.Format("20060102150405.000000000") + "-" + e.Kind
if err := scoped.Write(&store.Record{Key: key, Value: b}); err != nil {
t.Fatal(err)
}
}
got, err := ListRunSummaries(st, "runner")
if err != nil {
t.Fatal(err)
}
if len(got) != 2 {
t.Fatalf("got %d summaries, want 2: %#v", len(got), got)
}
if got[0].RunID != "run-a" || got[0].TraceID != "trace-a" || got[0].SpanID != "span-a" || got[0].Events != 2 || got[0].LastKind != "tool" || !got[0].UpdatedAt.Equal(time.Unix(0, 2)) {
t.Fatalf("unexpected run-a summary: %#v", got[0])
}
if got[1].RunID != "run-b" || got[1].ParentID != "parent" || got[1].Events != 2 || got[1].LastKind != "error" || got[1].LastError != "boom" {
t.Fatalf("unexpected run-b summary: %#v", got[1])
}
}
+267
View File
@@ -0,0 +1,267 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v3.21.12
// source: proto/agent.proto
package agent
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ChatRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChatRequest) Reset() {
*x = ChatRequest{}
mi := &file_proto_agent_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChatRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChatRequest) ProtoMessage() {}
func (x *ChatRequest) ProtoReflect() protoreflect.Message {
mi := &file_proto_agent_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ChatRequest.ProtoReflect.Descriptor instead.
func (*ChatRequest) Descriptor() ([]byte, []int) {
return file_proto_agent_proto_rawDescGZIP(), []int{0}
}
func (x *ChatRequest) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
type ChatResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Reply string `protobuf:"bytes,1,opt,name=reply,proto3" json:"reply,omitempty"`
Agent string `protobuf:"bytes,2,opt,name=agent,proto3" json:"agent,omitempty"`
ToolCalls []*ToolCall `protobuf:"bytes,3,rep,name=tool_calls,json=toolCalls,proto3" json:"tool_calls,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ChatResponse) Reset() {
*x = ChatResponse{}
mi := &file_proto_agent_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ChatResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ChatResponse) ProtoMessage() {}
func (x *ChatResponse) ProtoReflect() protoreflect.Message {
mi := &file_proto_agent_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ChatResponse.ProtoReflect.Descriptor instead.
func (*ChatResponse) Descriptor() ([]byte, []int) {
return file_proto_agent_proto_rawDescGZIP(), []int{1}
}
func (x *ChatResponse) GetReply() string {
if x != nil {
return x.Reply
}
return ""
}
func (x *ChatResponse) GetAgent() string {
if x != nil {
return x.Agent
}
return ""
}
func (x *ChatResponse) GetToolCalls() []*ToolCall {
if x != nil {
return x.ToolCalls
}
return nil
}
type ToolCall struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Input string `protobuf:"bytes,3,opt,name=input,proto3" json:"input,omitempty"`
Result string `protobuf:"bytes,4,opt,name=result,proto3" json:"result,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ToolCall) Reset() {
*x = ToolCall{}
mi := &file_proto_agent_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ToolCall) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ToolCall) ProtoMessage() {}
func (x *ToolCall) ProtoReflect() protoreflect.Message {
mi := &file_proto_agent_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ToolCall.ProtoReflect.Descriptor instead.
func (*ToolCall) Descriptor() ([]byte, []int) {
return file_proto_agent_proto_rawDescGZIP(), []int{2}
}
func (x *ToolCall) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *ToolCall) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *ToolCall) GetInput() string {
if x != nil {
return x.Input
}
return ""
}
func (x *ToolCall) GetResult() string {
if x != nil {
return x.Result
}
return ""
}
var File_proto_agent_proto protoreflect.FileDescriptor
const file_proto_agent_proto_rawDesc = "" +
"\n" +
"\x11proto/agent.proto\x12\x05agent\"'\n" +
"\vChatRequest\x12\x18\n" +
"\amessage\x18\x01 \x01(\tR\amessage\"j\n" +
"\fChatResponse\x12\x14\n" +
"\x05reply\x18\x01 \x01(\tR\x05reply\x12\x14\n" +
"\x05agent\x18\x02 \x01(\tR\x05agent\x12.\n" +
"\n" +
"tool_calls\x18\x03 \x03(\v2\x0f.agent.ToolCallR\ttoolCalls\"\\\n" +
"\bToolCall\x12\x0e\n" +
"\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" +
"\x04name\x18\x02 \x01(\tR\x04name\x12\x14\n" +
"\x05input\x18\x03 \x01(\tR\x05input\x12\x16\n" +
"\x06result\x18\x04 \x01(\tR\x06result2:\n" +
"\x05Agent\x121\n" +
"\x04Chat\x12\x12.agent.ChatRequest\x1a\x13.agent.ChatResponse\"\x00B\x0fZ\r./proto;agentb\x06proto3"
var (
file_proto_agent_proto_rawDescOnce sync.Once
file_proto_agent_proto_rawDescData []byte
)
func file_proto_agent_proto_rawDescGZIP() []byte {
file_proto_agent_proto_rawDescOnce.Do(func() {
file_proto_agent_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_agent_proto_rawDesc), len(file_proto_agent_proto_rawDesc)))
})
return file_proto_agent_proto_rawDescData
}
var file_proto_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_proto_agent_proto_goTypes = []any{
(*ChatRequest)(nil), // 0: agent.ChatRequest
(*ChatResponse)(nil), // 1: agent.ChatResponse
(*ToolCall)(nil), // 2: agent.ToolCall
}
var file_proto_agent_proto_depIdxs = []int32{
2, // 0: agent.ChatResponse.tool_calls:type_name -> agent.ToolCall
0, // 1: agent.Agent.Chat:input_type -> agent.ChatRequest
1, // 2: agent.Agent.Chat:output_type -> agent.ChatResponse
2, // [2:3] is the sub-list for method output_type
1, // [1:2] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_proto_agent_proto_init() }
func file_proto_agent_proto_init() {
if File_proto_agent_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_agent_proto_rawDesc), len(file_proto_agent_proto_rawDesc)),
NumEnums: 0,
NumMessages: 3,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_proto_agent_proto_goTypes,
DependencyIndexes: file_proto_agent_proto_depIdxs,
MessageInfos: file_proto_agent_proto_msgTypes,
}.Build()
File_proto_agent_proto = out.File
file_proto_agent_proto_goTypes = nil
file_proto_agent_proto_depIdxs = nil
}
+79
View File
@@ -0,0 +1,79 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: proto/agent.proto
package agent
import (
fmt "fmt"
proto "google.golang.org/protobuf/proto"
math "math"
)
import (
context "context"
client "go-micro.dev/v6/client"
server "go-micro.dev/v6/server"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ client.Option
var _ server.Option
// Client API for Agent service
type AgentService interface {
Chat(ctx context.Context, in *ChatRequest, opts ...client.CallOption) (*ChatResponse, error)
}
type agentService struct {
c client.Client
name string
}
func NewAgentService(name string, c client.Client) AgentService {
return &agentService{
c: c,
name: name,
}
}
func (c *agentService) Chat(ctx context.Context, in *ChatRequest, opts ...client.CallOption) (*ChatResponse, error) {
req := c.c.NewRequest(c.name, "Agent.Chat", in)
out := new(ChatResponse)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Agent service
type AgentHandler interface {
Chat(context.Context, *ChatRequest, *ChatResponse) error
}
func RegisterAgentHandler(s server.Server, hdlr AgentHandler, opts ...server.HandlerOption) error {
type agent interface {
Chat(ctx context.Context, in *ChatRequest, out *ChatResponse) error
}
type Agent struct {
agent
}
h := &agentHandler{hdlr}
return s.Handle(s.NewHandler(&Agent{h}, opts...))
}
type agentHandler struct {
AgentHandler
}
func (h *agentHandler) Chat(ctx context.Context, in *ChatRequest, out *ChatResponse) error {
return h.AgentHandler.Chat(ctx, in, out)
}
+27
View File
@@ -0,0 +1,27 @@
syntax = "proto3";
package agent;
option go_package = "./proto;agent";
// Agent is the RPC interface for an AI agent.
service Agent {
rpc Chat(ChatRequest) returns (ChatResponse) {}
}
message ChatRequest {
string message = 1;
}
message ChatResponse {
string reply = 1;
string agent = 2;
repeated ToolCall tool_calls = 3;
}
message ToolCall {
string id = 1;
string name = 2;
string input = 3;
string result = 4;
}
+77
View File
@@ -0,0 +1,77 @@
package agent
import (
"context"
"errors"
"testing"
"time"
"go-micro.dev/v6/ai"
)
func TestAskCancellationAbortsPromptly(t *testing.T) {
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
<-ctx.Done()
return nil, ctx.Err()
}
defer func() { fakeGen = nil }()
a := newTestAgent(Name("cancel"), ModelCallTimeout(time.Second), ModelRetry(3, time.Millisecond))
ctx, cancel := context.WithCancel(context.Background())
cancel()
start := time.Now()
_, err := a.Ask(ctx, "stop")
if !errors.Is(err, context.Canceled) {
t.Fatalf("Ask error = %v, want context canceled", err)
}
if elapsed := time.Since(start); elapsed > 100*time.Millisecond {
t.Fatalf("Ask took %s after cancellation, want prompt abort", elapsed)
}
}
func TestAskRetriesTransientErrorsThenSucceeds(t *testing.T) {
attempts := 0
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
attempts++
if attempts < 3 {
return nil, context.DeadlineExceeded
}
return &ai.Response{Reply: "ok"}, nil
}
defer func() { fakeGen = nil }()
a := newTestAgent(Name("retry-success"), ModelRetry(3, time.Millisecond))
resp, err := a.Ask(context.Background(), "hello")
if err != nil {
t.Fatalf("Ask returned error: %v", err)
}
if resp.Reply != "ok" {
t.Fatalf("reply = %q, want ok", resp.Reply)
}
if attempts != 3 {
t.Fatalf("attempts = %d, want 3", attempts)
}
}
func TestAskRetriesTransientErrorsThenSurfacesStructuredError(t *testing.T) {
attempts := 0
fakeGen = func(ctx context.Context, opts ai.Options, req *ai.Request) (*ai.Response, error) {
attempts++
return nil, context.DeadlineExceeded
}
defer func() { fakeGen = nil }()
a := newTestAgent(Name("retry-fail"), ModelRetry(2, time.Millisecond))
_, err := a.Ask(context.Background(), "hello")
var retryErr *ai.RetryError
if !errors.As(err, &retryErr) {
t.Fatalf("Ask error = %T %v, want *ai.RetryError", err, err)
}
if retryErr.Attempts != 2 {
t.Fatalf("retry attempts = %d, want 2", retryErr.Attempts)
}
if attempts != 2 {
t.Fatalf("model attempts = %d, want 2", attempts)
}
}
+183
View File
@@ -0,0 +1,183 @@
package agent
import (
"context"
"fmt"
"strings"
"testing"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
)
// A registered wrapper runs around every tool call and can observe and
// modify the result.
func TestWrapToolWraps(t *testing.T) {
var saw string
wrap := func(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
saw = call.Name
res := next(ctx, call)
res.Content = "wrapped:" + res.Content
return res
}
}
a := newTestAgent(Name("wrapped"), WrapTool(wrap))
content := toolContent(a.toolHandler(), "demo_Svc_Do", map[string]any{})
if saw != "demo_Svc_Do" {
t.Errorf("wrapper saw %q, want demo_Svc_Do", saw)
}
if !strings.HasPrefix(content, "wrapped:") {
t.Errorf("wrapper did not modify the result; got %q", content)
}
}
// Multiple wrappers compose outermost-first: the first registered wrapper
// is the outer layer, so it runs first on the way in and last on the way
// out.
func TestWrapToolOrder(t *testing.T) {
var order []string
mk := func(tag string) ai.ToolWrapper {
return func(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
order = append(order, "in:"+tag)
res := next(ctx, call)
order = append(order, "out:"+tag)
return res
}
}
}
a := newTestAgent(Name("ordered"), WrapTool(mk("a"), mk("b")))
toolContent(a.toolHandler(), "demo_Svc_Do", map[string]any{})
want := "in:a in:b out:b out:a"
if got := strings.Join(order, " "); got != want {
t.Errorf("wrapper order = %q, want %q", got, want)
}
}
// Wrappers run outside the built-in guardrails, so they observe a refused
// call and its refusal result rather than being short-circuited.
func TestWrapToolSeesGuardrailRefusal(t *testing.T) {
var sawResult string
wrap := func(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
res := next(ctx, call)
sawResult = res.Content
return res
}
}
a := newTestAgent(Name("gated-wrap"),
ApproveTool(func(tool string, input map[string]any) (bool, string) {
return false, "denied"
}),
WrapTool(wrap),
)
toolContent(a.toolHandler(), "demo_Svc_Do", map[string]any{})
if !strings.Contains(sawResult, "not approved") {
t.Errorf("wrapper should observe the guardrail refusal; got %q", sawResult)
}
}
// A guardrail refusal carries a structured reason a wrapper can switch on,
// so reliability tooling (e.g. loop handling) needn't parse the message.
func TestWrapToolSeesRefusedReason(t *testing.T) {
a := newTestAgent(Name("looper"), LoopLimit(2))
h := a.toolHandler()
var last ai.ToolResult
for i := 0; i < 3; i++ {
last = h(context.Background(), ai.ToolCall{ID: "x", Name: "demo_Svc_Do", Input: map[string]any{"q": "same"}})
}
if last.Refused != ai.RefusedLoop {
t.Errorf("Refused = %q, want %q", last.Refused, ai.RefusedLoop)
}
}
// ctxMock is a model that forwards the Generate context to the tool
// handler (as real providers do), so a wrapper can read ai.RunInfo.
type ctxMock struct{ opts ai.Options }
func (m *ctxMock) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&m.opts)
}
return nil
}
func (m *ctxMock) Options() ai.Options { return m.opts }
func (m *ctxMock) String() string { return "ctxmock" }
func (m *ctxMock) Stream(context.Context, *ai.Request, ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("no stream")
}
func (m *ctxMock) Generate(ctx context.Context, _ *ai.Request, _ ...ai.GenerateOption) (*ai.Response, error) {
if m.opts.ToolHandler != nil {
m.opts.ToolHandler(ctx, ai.ToolCall{ID: "c1", Name: "demo_Svc_Do", Input: map[string]any{}})
}
return &ai.Response{Answer: "done"}, nil
}
// During an Ask, a wrapper sees RunInfo on the context: a correlation id
// for the run and the agent's name.
func TestWrapToolSeesRunInfo(t *testing.T) {
ai.Register("ctxmock", func(opts ...ai.Option) ai.Model {
m := &ctxMock{}
_ = m.Init(opts...)
return m
})
var got ai.RunInfo
var ok bool
a := New(
Name("runner"),
Provider("ctxmock"),
WithRegistry(registry.NewMemoryRegistry()),
WithStore(store.NewMemoryStore()),
WrapTool(func(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
got, ok = ai.RunInfoFrom(ctx)
return next(ctx, call)
}
}),
)
resp, err := a.Ask(context.Background(), "go")
if err != nil {
t.Fatalf("Ask: %v", err)
}
if !ok {
t.Fatal("wrapper did not see RunInfo on the context")
}
if got.Agent != "runner" {
t.Errorf("RunInfo.Agent = %q, want runner", got.Agent)
}
if got.RunID == "" {
t.Error("RunInfo.RunID is empty")
}
if resp.RunID != got.RunID {
t.Errorf("Response.RunID = %q, want wrapper RunID %q", resp.RunID, got.RunID)
}
if resp.ParentID != "" {
t.Errorf("Response.ParentID = %q, want empty", resp.ParentID)
}
}
// call.Scan decodes a tool call's input into a typed struct.
func TestToolCallScan(t *testing.T) {
call := ai.ToolCall{Input: map[string]any{"query": "hello", "limit": 5}}
var args struct {
Query string `json:"query"`
Limit int `json:"limit"`
}
if err := call.Scan(&args); err != nil {
t.Fatalf("Scan: %v", err)
}
if args.Query != "hello" || args.Limit != 5 {
t.Errorf("Scan decoded %+v, want {hello 5}", args)
}
}
+351
View File
@@ -0,0 +1,351 @@
# AI Package
The `ai` package provides simple, high-level interfaces for AI model providers. It supports text generation (`Model`), image generation (`ImageModel`), and video generation (`VideoModel`).
## Interfaces
### Text Generation (Model)
The Model interface follows the same patterns as other go-micro packages (Registry, Client, Broker):
```go
type Model interface {
Init(...Option) error
Options() Options
Generate(ctx context.Context, req *Request, opts ...GenerateOption) (*Response, error)
Stream(ctx context.Context, req *Request, opts ...GenerateOption) (Stream, error)
String() string
}
```
## Quick Start
```go
import (
"context"
"go-micro.dev/v5/ai"
_ "go-micro.dev/v5/ai/anthropic"
_ "go-micro.dev/v5/ai/openai"
)
// Create a model
m := ai.New("openai",
ai.WithAPIKey("your-api-key"),
ai.WithModel("gpt-4o"),
)
// Generate a response
req := &ai.Request{
Prompt: "What is Go?",
SystemPrompt: "You are a helpful programming assistant",
}
resp, err := m.Generate(context.Background(), req)
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Reply)
```
### Image Generation (ImageModel)
```go
type ImageModel interface {
GenerateImage(ctx context.Context, req *ImageRequest, opts ...GenerateOption) (*ImageResponse, error)
String() string
}
```
```go
import (
"go-micro.dev/v5/ai"
_ "go-micro.dev/v5/ai/atlascloud"
)
ig := ai.NewImage("atlascloud",
ai.WithAPIKey("your-api-key"),
)
resp, err := ig.GenerateImage(context.Background(), &ai.ImageRequest{
Prompt: "A Go gopher in space",
Size: "1024x1024",
})
fmt.Println(resp.Images[0].URL)
```
Providers that support image generation: **Atlas Cloud**, **OpenAI**.
### Video Generation (VideoModel)
```go
type VideoModel interface {
GenerateVideo(ctx context.Context, req *VideoRequest, opts ...GenerateOption) (*VideoResponse, error)
String() string
}
```
```go
import (
"go-micro.dev/v5/ai"
_ "go-micro.dev/v5/ai/atlascloud"
)
vg := ai.NewVideo("atlascloud",
ai.WithAPIKey("your-api-key"),
)
resp, err := vg.GenerateVideo(context.Background(), &ai.VideoRequest{
Prompt: "Microservices nodes animating with data flowing between them",
Images: []string{"https://example.com/diagram.png"}, // optional: image-to-video
Duration: 6,
})
fmt.Println(resp.URL)
```
Providers that support video generation: **Atlas Cloud**.
## Options
Configure the model using functional options:
```go
m := ai.New("anthropic",
ai.WithAPIKey("your-key"), // Required
ai.WithModel("claude-sonnet-4-20250514"), // Optional, uses provider default
ai.WithBaseURL("https://api.anthropic.com"), // Optional, uses provider default
)
```
You can also update options after creation:
```go
m.Init(
ai.WithModel("gpt-4o-mini"),
ai.WithAPIKey("new-key"),
)
```
## Using Tools
The model can automatically execute tool calls when provided with a tool handler:
```go
// Define a tool handler. It mirrors a go-micro RPC handler: context
// first, the call in, a result out.
toolHandler := func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
// Execute the tool and return results
switch call.Name {
case "get_weather":
return ai.ToolResult{ID: call.ID, Value: map[string]string{"temp": "72F"}, Content: `{"temp": "72F"}`}
default:
return ai.ToolResult{ID: call.ID, Content: `{"error": "unknown tool"}`}
}
}
// Create model with tool handler
m := ai.New("openai",
ai.WithAPIKey("your-key"),
ai.WithToolHandler(toolHandler),
)
// Provide tools in the request
req := &ai.Request{
Prompt: "What's the weather?",
SystemPrompt: "You are a helpful assistant",
Tools: []ai.Tool{
{
Name: "get_weather",
Description: "Get current weather",
Properties: map[string]any{
"location": map[string]any{
"type": "string",
"description": "City name",
},
},
},
},
}
// Generate will automatically call tools and return final answer
resp, err := m.Generate(context.Background(), req)
fmt.Println(resp.Answer) // Final answer after tool execution
```
## Response Structure
```go
type Response struct {
Reply string // Initial reply from model
ToolCalls []ToolCall // Tools the model wants to call
Answer string // Final answer (after tool execution if handler provided)
}
```
- `Reply`: The model's first response
- `ToolCalls`: List of tools the model requested (if any)
- `Answer`: The final answer after tools are executed (only set if ToolHandler is provided)
## Supported Providers
### Anthropic Claude
```go
m := ai.New("anthropic",
ai.WithAPIKey("sk-ant-..."),
ai.WithModel("claude-sonnet-4-20250514"), // default
)
```
Default model: `claude-sonnet-4-20250514`
Default base URL: `https://api.anthropic.com`
### OpenAI GPT
```go
m := ai.New("openai",
ai.WithAPIKey("sk-..."),
ai.WithModel("gpt-4o"), // default
)
```
Default model: `gpt-4o`
Default base URL: `https://api.openai.com`
### Google Gemini
```go
m := ai.New("gemini",
ai.WithAPIKey("your-key"),
ai.WithModel("gemini-2.5-flash"), // default
)
```
Default model: `gemini-2.5-flash`
Default base URL: `https://generativelanguage.googleapis.com`
Google Gemini uses its own API format with `system_instruction`, `contents` (not `messages`), and `functionDeclarations` for tool calling. The provider handles the translation automatically.
### Groq
```go
m := ai.New("groq",
ai.WithAPIKey("your-key"),
ai.WithModel("llama-3.3-70b-versatile"), // default
)
```
Default model: `llama-3.3-70b-versatile`
Default base URL: `https://api.groq.com/openai`
Groq provides ultra-fast inference for open-weight models via an OpenAI-compatible endpoint.
### Mistral
```go
m := ai.New("mistral",
ai.WithAPIKey("your-key"),
ai.WithModel("mistral-large-latest"), // default
)
```
Default model: `mistral-large-latest`
Default base URL: `https://api.mistral.ai`
Mistral AI is a European AI company offering high-performance models via an OpenAI-compatible endpoint.
### Together AI
```go
m := ai.New("together",
ai.WithAPIKey("your-key"),
ai.WithModel("meta-llama/Llama-3.3-70B-Instruct-Turbo"), // default
)
```
Default model: `meta-llama/Llama-3.3-70B-Instruct-Turbo`
Default base URL: `https://api.together.xyz`
Together AI provides fast inference for open-weight models via an OpenAI-compatible endpoint.
### Atlas Cloud
```go
m := ai.New("atlascloud",
ai.WithAPIKey("your-key"),
ai.WithModel("llama-3.3-70b"), // default
)
```
Default model: `llama-3.3-70b`
Default base URL: `https://api.atlascloud.ai`
Atlas Cloud is an enterprise AI infrastructure platform offering high-performance LLM APIs. It exposes an OpenAI-compatible chat completions endpoint with tool calling support.
## Auto-Detection
Use `AutoDetectProvider()` to detect the provider from a base URL:
```go
provider := ai.AutoDetectProvider("https://api.anthropic.com")
// Returns "anthropic"
m := ai.New(provider, ai.WithAPIKey("..."))
```
## Adding a New Provider
See the full **[AI Provider Integration Guide](../internal/website/docs/guides/ai-provider-guide.md)** for a step-by-step walkthrough, checklist, and design notes.
Quick summary:
1. Create `ai/yourprovider/yourprovider.go` implementing `ai.Model`.
2. Call `ai.Register("yourprovider", ...)` in `init()`.
3. Add tests in `ai/yourprovider/yourprovider_test.go`.
4. Users enable the provider with a blank import:
```go
import _ "go-micro.dev/v5/ai/yourprovider"
```
We welcome contributions and sponsorships from AI infrastructure companies — see the guide for details.
## Comparison with Other Packages
The ai package follows the same patterns as other go-micro packages:
**Registry:**
```go
r := registry.NewRegistry(registry.Addrs("..."))
r.Register(service)
```
**Client:**
```go
c := client.NewClient(client.Retries(3))
c.Call(ctx, req, rsp)
```
**AI:**
```go
m := ai.New("openai", ai.WithAPIKey("..."))
m.Generate(ctx, req)
```
All use:
- `Init()` to update options
- `Options()` to get current options
- `String()` to get the implementation name
- Functional options pattern
## Testing
```bash
go test ./ai/...
```
## Examples
See the [server implementation](../cmd/micro/server/server.go) for a complete example of using the ai package with tool execution.
+272
View File
@@ -0,0 +1,272 @@
// Package anthropic implements the Anthropic Claude model provider
package anthropic
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"go-micro.dev/v6/ai"
)
func init() {
ai.Register("anthropic", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
}
// Provider implements the ai.Model interface for Anthropic Claude
type Provider struct {
opts ai.Options
}
// NewProvider creates a new Anthropic provider
func NewProvider(opts ...ai.Option) *Provider {
options := ai.NewOptions(opts...)
// Set defaults if not provided
if options.Model == "" {
options.Model = "claude-sonnet-4-20250514"
}
if options.BaseURL == "" {
options.BaseURL = "https://api.anthropic.com"
}
return &Provider{
opts: options,
}
}
// Init initializes the provider with options
func (p *Provider) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&p.opts)
}
return nil
}
// Options returns the provider options
func (p *Provider) Options() ai.Options {
return p.opts
}
// String returns the provider name
func (p *Provider) String() string {
return "anthropic"
}
// Generate generates a response from the model
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
// Build tools for Anthropic format
var anthropicTools []map[string]any
for _, t := range req.Tools {
anthropicTools = append(anthropicTools, map[string]any{
"name": t.Name,
"description": t.Description,
"input_schema": map[string]any{
"type": "object",
"properties": t.Properties,
},
})
}
// Build initial request
apiReq := map[string]any{
"model": p.opts.Model,
"max_tokens": 8192,
"system": req.SystemPrompt,
"messages": []map[string]any{
{"role": "user", "content": req.Prompt},
},
}
if len(anthropicTools) > 0 {
apiReq["tools"] = anthropicTools
}
// Make API call
resp, rawContent, err := p.callAPI(ctx, apiReq)
if err != nil {
return nil, err
}
// If no tool calls or no handler, return as-is
if len(resp.ToolCalls) == 0 || p.opts.ToolHandler == nil {
return resp, nil
}
// Tool execution loop: execute tools, send results back, repeat
// until the model responds with text only (no more tool calls)
messages := []map[string]any{
{"role": "user", "content": req.Prompt},
{"role": "assistant", "content": cleanContent(rawContent)},
}
pendingCalls := resp.ToolCalls
for rounds := 0; rounds < 10; rounds++ {
var toolResultBlocks []map[string]any
for i := range pendingCalls {
content := p.opts.ToolHandler(ctx, pendingCalls[i]).Content
pendingCalls[i].Result = content
toolResultBlocks = append(toolResultBlocks, map[string]any{
"type": "tool_result",
"tool_use_id": pendingCalls[i].ID,
"content": content,
})
}
messages = append(messages, map[string]any{
"role": "user",
"content": toolResultBlocks,
})
followUpReq := map[string]any{
"model": p.opts.Model,
"max_tokens": 8192,
"system": req.SystemPrompt,
"messages": messages,
}
if len(anthropicTools) > 0 {
followUpReq["tools"] = anthropicTools
}
followUpResp, followUpRaw, err := p.callAPI(ctx, followUpReq)
if err != nil {
break
}
if len(followUpResp.ToolCalls) > 0 {
resp.ToolCalls = append(resp.ToolCalls, followUpResp.ToolCalls...)
pendingCalls = followUpResp.ToolCalls
messages = append(messages, map[string]any{
"role": "assistant",
"content": cleanContent(followUpRaw),
})
continue
}
if followUpResp.Reply != "" {
resp.Answer = followUpResp.Reply
}
break
}
return resp, nil
}
// Stream generates a streaming response (not yet implemented)
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("streaming not yet implemented for anthropic provider")
}
// callAPI makes an HTTP request to the Anthropic API
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, any, error) {
// Marshal request
reqBody, err := json.Marshal(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
// Build HTTP request
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/messages"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
// Set headers
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("x-api-key", p.opts.APIKey)
httpReq.Header.Set("anthropic-version", "2023-06-01")
// Make request
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
// Read response
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
// Parse response
var anthropicResp struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
} `json:"content"`
StopReason string `json:"stop_reason"`
}
if err := json.Unmarshal(respBody, &anthropicResp); err != nil {
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
}
response := &ai.Response{}
// Extract text reply
var replyParts []string
for _, block := range anthropicResp.Content {
if block.Type == "text" && block.Text != "" {
replyParts = append(replyParts, block.Text)
}
}
if len(replyParts) > 0 {
response.Reply = strings.Join(replyParts, "\n")
}
// Extract tool calls
for _, block := range anthropicResp.Content {
if block.Type == "tool_use" {
var input map[string]any
if err := json.Unmarshal(block.Input, &input); err != nil {
input = map[string]any{}
}
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
ID: block.ID,
Name: block.Name,
Input: input,
})
}
}
return response, anthropicResp.Content, nil
}
// cleanContent strips fields from response content blocks that Anthropic
// rejects when sent back as assistant message content (e.g. "id" on text blocks).
func cleanContent(raw any) any {
blocks, ok := raw.([]struct {
Type string `json:"type"`
Text string `json:"text"`
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
})
if !ok {
return raw
}
var cleaned []map[string]any
for _, b := range blocks {
switch b.Type {
case "text":
cleaned = append(cleaned, map[string]any{"type": "text", "text": b.Text})
case "tool_use":
var input any
_ = json.Unmarshal(b.Input, &input)
cleaned = append(cleaned, map[string]any{"type": "tool_use", "id": b.ID, "name": b.Name, "input": input})
}
}
return cleaned
}
+94
View File
@@ -0,0 +1,94 @@
package anthropic
import (
"context"
"testing"
"go-micro.dev/v6/ai"
)
func TestProvider_String(t *testing.T) {
p := NewProvider()
if p.String() != "anthropic" {
t.Errorf("Expected provider name 'anthropic', got '%s'", p.String())
}
}
func TestProvider_Init(t *testing.T) {
p := NewProvider()
err := p.Init(
ai.WithModel("test-model"),
ai.WithAPIKey("test-key"),
ai.WithBaseURL("https://test.com"),
)
if err != nil {
t.Fatalf("Init failed: %v", err)
}
opts := p.Options()
if opts.Model != "test-model" {
t.Errorf("Expected model 'test-model', got '%s'", opts.Model)
}
if opts.APIKey != "test-key" {
t.Errorf("Expected API key 'test-key', got '%s'", opts.APIKey)
}
if opts.BaseURL != "https://test.com" {
t.Errorf("Expected base URL 'https://test.com', got '%s'", opts.BaseURL)
}
}
func TestProvider_Options(t *testing.T) {
p := NewProvider(
ai.WithModel("custom-model"),
ai.WithAPIKey("my-key"),
)
opts := p.Options()
if opts.Model != "custom-model" {
t.Errorf("Expected model 'custom-model', got '%s'", opts.Model)
}
if opts.APIKey != "my-key" {
t.Errorf("Expected API key 'my-key', got '%s'", opts.APIKey)
}
}
func TestProvider_Defaults(t *testing.T) {
p := NewProvider()
opts := p.Options()
if opts.Model != "claude-sonnet-4-20250514" {
t.Errorf("Expected default model 'claude-sonnet-4-20250514', got '%s'", opts.Model)
}
if opts.BaseURL != "https://api.anthropic.com" {
t.Errorf("Expected default base URL 'https://api.anthropic.com', got '%s'", opts.BaseURL)
}
}
func TestProvider_Generate_NoAPIKey(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
SystemPrompt: "You are helpful",
}
_, err := p.Generate(context.Background(), req)
if err == nil {
t.Error("Expected error when API key is missing, got nil")
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
}
_, err := p.Stream(context.Background(), req)
if err == nil {
t.Error("Expected error for unimplemented streaming, got nil")
}
}
+489
View File
@@ -0,0 +1,489 @@
// Package atlascloud implements the Atlas Cloud model provider.
//
// Atlas Cloud is an enterprise AI infrastructure platform offering
// high-performance LLM, image, and video APIs. It exposes
// OpenAI-compatible endpoints for chat completions and image
// generation.
//
// Usage:
//
// import _ "go-micro.dev/v6/ai/atlascloud"
//
// m := ai.New("atlascloud",
// ai.WithAPIKey("your-api-key"),
// )
//
// // Image generation
// ig := ai.NewImage("atlascloud",
// ai.WithAPIKey("your-api-key"),
// )
package atlascloud
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"go-micro.dev/v6/ai"
)
func init() {
ai.Register("atlascloud", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
ai.RegisterImage("atlascloud", func(opts ...ai.Option) ai.ImageModel {
return NewProvider(opts...)
})
ai.RegisterVideo("atlascloud", func(opts ...ai.Option) ai.VideoModel {
return NewProvider(opts...)
})
}
// Provider implements the ai.Model interface for Atlas Cloud.
type Provider struct {
opts ai.Options
}
// NewProvider creates a new Atlas Cloud provider.
func NewProvider(opts ...ai.Option) *Provider {
options := ai.NewOptions(opts...)
if options.Model == "" {
options.Model = "deepseek-ai/DeepSeek-V3-0324"
}
if options.BaseURL == "" {
options.BaseURL = "https://api.atlascloud.ai"
}
return &Provider{opts: options}
}
func (p *Provider) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&p.opts)
}
return nil
}
func (p *Provider) Options() ai.Options { return p.opts }
func (p *Provider) String() string { return "atlascloud" }
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
var tools []map[string]any
for _, t := range req.Tools {
tools = append(tools, map[string]any{
"type": "function",
"function": map[string]any{
"name": t.Name,
"description": t.Description,
"parameters": map[string]any{
"type": "object",
"properties": t.Properties,
},
},
})
}
messages := []map[string]any{
{"role": "system", "content": req.SystemPrompt},
{"role": "user", "content": req.Prompt},
}
apiReq := map[string]any{
"model": p.opts.Model,
"messages": messages,
}
if len(tools) > 0 {
apiReq["tools"] = tools
}
resp, rawMessage, err := p.callAPI(ctx, apiReq)
if err != nil {
return nil, err
}
if len(resp.ToolCalls) == 0 {
return resp, nil
}
if p.opts.ToolHandler != nil {
followUpMessages := append(messages, map[string]any{
"role": "assistant",
"content": rawMessage["content"],
"tool_calls": rawMessage["tool_calls"],
})
for _, tc := range resp.ToolCalls {
content := p.opts.ToolHandler(ctx, tc).Content
followUpMessages = append(followUpMessages, map[string]any{
"role": "tool",
"tool_call_id": tc.ID,
"content": content,
})
}
followUpReq := map[string]any{
"model": p.opts.Model,
"messages": followUpMessages,
}
followUpResp, _, err := p.callAPI(ctx, followUpReq)
if err == nil && followUpResp.Reply != "" {
resp.Answer = followUpResp.Reply
}
}
return resp, nil
}
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("streaming not yet implemented for atlascloud provider")
}
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, map[string]any, error) {
reqBody, err := json.Marshal(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/chat/completions"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var chatResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ToolCalls []struct {
ID string `json:"id"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
} `json:"tool_calls"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &chatResp); err != nil {
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(chatResp.Choices) == 0 {
return nil, nil, fmt.Errorf("no response from API")
}
choice := chatResp.Choices[0]
response := &ai.Response{
Reply: choice.Message.Content,
}
for _, tc := range choice.Message.ToolCalls {
var input map[string]any
if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
input = map[string]any{}
}
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
ID: tc.ID,
Name: tc.Function.Name,
Input: input,
})
}
rawMessage := map[string]any{
"content": choice.Message.Content,
"tool_calls": choice.Message.ToolCalls,
}
return response, rawMessage, nil
}
const defaultImageModel = "openai/gpt-image-2/text-to-image"
// GenerateImage creates an image using Atlas Cloud's async image API.
// It submits the job and polls until completion or context cancellation.
func (p *Provider) GenerateImage(ctx context.Context, req *ai.ImageRequest, opts ...ai.GenerateOption) (*ai.ImageResponse, error) {
model := req.Model
if model == "" {
model = defaultImageModel
}
quality := req.Quality
if quality == "" {
quality = "medium"
}
outputFmt := req.OutputFormat
if outputFmt == "" {
outputFmt = "png"
}
size := req.Size
if size == "" {
size = "1024x1024"
}
apiReq := map[string]any{
"model": model,
"prompt": req.Prompt,
"quality": quality,
"output_format": outputFmt,
"size": size,
"enable_sync_mode": false,
"enable_base64_output": false,
"moderation": "low",
}
reqBody, err := json.Marshal(apiReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/api/v1/model/generateImage"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var submitResp struct {
Code int `json:"code"`
Msg string `json:"message"`
Data struct {
ID string `json:"id"`
Status string `json:"status"`
} `json:"data"`
}
if err := json.Unmarshal(respBody, &submitResp); err != nil {
return nil, fmt.Errorf("failed to parse submit response: %w", err)
}
if submitResp.Code != 200 {
return nil, fmt.Errorf("API error: %s", submitResp.Msg)
}
predictionID := submitResp.Data.ID
pollURL := strings.TrimRight(p.opts.BaseURL, "/") + "/api/v1/model/prediction/" + predictionID
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
result, err := p.pollPrediction(ctx, pollURL)
if err != nil {
return nil, err
}
if result != nil {
return result, nil
}
}
}
}
func (p *Provider) pollPrediction(ctx context.Context, url string) (*ai.ImageResponse, error) {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("poll request failed: %w", err)
}
defer httpResp.Body.Close()
body, _ := io.ReadAll(httpResp.Body)
var pollResp struct {
Data struct {
Status string `json:"status"`
Outputs []string `json:"outputs"`
Error string `json:"error"`
} `json:"data"`
}
if err := json.Unmarshal(body, &pollResp); err != nil {
return nil, fmt.Errorf("failed to parse poll response: %w", err)
}
switch pollResp.Data.Status {
case "completed":
resp := &ai.ImageResponse{}
for _, output := range pollResp.Data.Outputs {
resp.Images = append(resp.Images, ai.Image{URL: output})
}
return resp, nil
case "failed":
return nil, fmt.Errorf("image generation failed: %s", pollResp.Data.Error)
default:
return nil, nil
}
}
const defaultVideoModel = "google/gemini-omni-flash/image-to-video-developer"
// GenerateVideo creates a video using Atlas Cloud's async video API.
// Supports text-to-video and image-to-video depending on whether
// Images are provided in the request.
func (p *Provider) GenerateVideo(ctx context.Context, req *ai.VideoRequest, opts ...ai.GenerateOption) (*ai.VideoResponse, error) {
model := req.Model
if model == "" {
model = defaultVideoModel
}
duration := req.Duration
if duration <= 0 {
duration = 6
}
aspect := req.AspectRatio
if aspect == "" {
aspect = "16:9"
}
resolution := req.Resolution
if resolution == "" {
resolution = "720p"
}
apiReq := map[string]any{
"model": model,
"prompt": req.Prompt,
"duration": duration,
"aspect_ratio": aspect,
"resolution": resolution,
"seed": -1,
}
if len(req.Images) > 0 {
apiReq["images"] = req.Images
}
reqBody, err := json.Marshal(apiReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/api/v1/model/generateVideo"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var submitResp struct {
Code int `json:"code"`
Msg string `json:"message"`
Data struct {
ID string `json:"id"`
Status string `json:"status"`
} `json:"data"`
}
if err := json.Unmarshal(respBody, &submitResp); err != nil {
return nil, fmt.Errorf("failed to parse submit response: %w", err)
}
if submitResp.Code != 200 {
return nil, fmt.Errorf("API error: %s", submitResp.Msg)
}
pollURL := strings.TrimRight(p.opts.BaseURL, "/") + "/api/v1/model/prediction/" + submitResp.Data.ID
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-ticker.C:
result, err := p.pollVideo(ctx, pollURL)
if err != nil {
return nil, err
}
if result != nil {
return result, nil
}
}
}
}
func (p *Provider) pollVideo(ctx context.Context, url string) (*ai.VideoResponse, error) {
httpReq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("poll request failed: %w", err)
}
defer httpResp.Body.Close()
body, _ := io.ReadAll(httpResp.Body)
var pollResp struct {
Data struct {
Status string `json:"status"`
Outputs []string `json:"outputs"`
Error string `json:"error"`
} `json:"data"`
}
if err := json.Unmarshal(body, &pollResp); err != nil {
return nil, fmt.Errorf("failed to parse poll response: %w", err)
}
switch pollResp.Data.Status {
case "completed", "succeeded":
if len(pollResp.Data.Outputs) == 0 {
return nil, fmt.Errorf("video completed but no outputs returned")
}
return &ai.VideoResponse{URL: pollResp.Data.Outputs[0]}, nil
case "failed":
return nil, fmt.Errorf("video generation failed: %s", pollResp.Data.Error)
default:
return nil, nil
}
}
+148
View File
@@ -0,0 +1,148 @@
package atlascloud
import (
"context"
"testing"
"go-micro.dev/v6/ai"
)
func TestProvider_String(t *testing.T) {
p := NewProvider()
if p.String() != "atlascloud" {
t.Errorf("Expected provider name 'atlascloud', got '%s'", p.String())
}
}
func TestProvider_Init(t *testing.T) {
p := NewProvider()
err := p.Init(
ai.WithModel("test-model"),
ai.WithAPIKey("test-key"),
ai.WithBaseURL("https://test.com"),
)
if err != nil {
t.Fatalf("Init failed: %v", err)
}
opts := p.Options()
if opts.Model != "test-model" {
t.Errorf("Expected model 'test-model', got '%s'", opts.Model)
}
if opts.APIKey != "test-key" {
t.Errorf("Expected API key 'test-key', got '%s'", opts.APIKey)
}
if opts.BaseURL != "https://test.com" {
t.Errorf("Expected base URL 'https://test.com', got '%s'", opts.BaseURL)
}
}
func TestProvider_Options(t *testing.T) {
p := NewProvider(
ai.WithModel("custom-model"),
ai.WithAPIKey("my-key"),
)
opts := p.Options()
if opts.Model != "custom-model" {
t.Errorf("Expected model 'custom-model', got '%s'", opts.Model)
}
if opts.APIKey != "my-key" {
t.Errorf("Expected API key 'my-key', got '%s'", opts.APIKey)
}
}
func TestProvider_Defaults(t *testing.T) {
p := NewProvider()
opts := p.Options()
if opts.Model != "deepseek-ai/DeepSeek-V3-0324" {
t.Errorf("Expected default model 'deepseek-ai/DeepSeek-V3-0324', got '%s'", opts.Model)
}
if opts.BaseURL != "https://api.atlascloud.ai" {
t.Errorf("Expected default base URL 'https://api.atlascloud.ai', got '%s'", opts.BaseURL)
}
}
func TestProvider_Generate_NoAPIKey(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
SystemPrompt: "You are helpful",
}
_, err := p.Generate(context.Background(), req)
if err == nil {
t.Error("Expected error when API key is missing, got nil")
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
}
_, err := p.Stream(context.Background(), req)
if err == nil {
t.Error("Expected error for unimplemented streaming, got nil")
}
}
func TestProvider_Registration(t *testing.T) {
m := ai.New("atlascloud", ai.WithAPIKey("test"))
if m == nil {
t.Fatal("ai.New('atlascloud') returned nil — provider not registered")
}
if m.String() != "atlascloud" {
t.Errorf("Expected 'atlascloud', got '%s'", m.String())
}
}
func TestProvider_ImageRegistration(t *testing.T) {
ig := ai.NewImage("atlascloud", ai.WithAPIKey("test"))
if ig == nil {
t.Fatal("ai.NewImage('atlascloud') returned nil — image provider not registered")
}
if ig.String() != "atlascloud" {
t.Errorf("Expected 'atlascloud', got '%s'", ig.String())
}
}
func TestProvider_GenerateImage_NoAPIKey(t *testing.T) {
p := NewProvider()
_, err := p.GenerateImage(context.Background(), &ai.ImageRequest{Prompt: "a cat"})
if err == nil {
t.Error("Expected error when API key is missing, got nil")
}
}
func TestProvider_ImplementsImageModel(t *testing.T) {
var _ ai.ImageModel = (*Provider)(nil)
}
func TestProvider_VideoRegistration(t *testing.T) {
vg := ai.NewVideo("atlascloud", ai.WithAPIKey("test"))
if vg == nil {
t.Fatal("ai.NewVideo('atlascloud') returned nil — video provider not registered")
}
if vg.String() != "atlascloud" {
t.Errorf("Expected 'atlascloud', got '%s'", vg.String())
}
}
func TestProvider_GenerateVideo_NoAPIKey(t *testing.T) {
p := NewProvider()
_, err := p.GenerateVideo(context.Background(), &ai.VideoRequest{Prompt: "a cat"})
if err == nil {
t.Error("Expected error when API key is missing, got nil")
}
}
func TestProvider_ImplementsVideoModel(t *testing.T) {
var _ ai.VideoModel = (*Provider)(nil)
}
+22
View File
@@ -0,0 +1,22 @@
// Package flow is maintained for backward compatibility.
// The canonical import is go-micro.dev/v6/flow.
package flow
import "go-micro.dev/v6/flow"
// Re-export types for backward compatibility.
type Flow = flow.Flow
type Options = flow.Options
type Option = flow.Option
type Result = flow.Result
var New = flow.New
var Trigger = flow.Trigger
var Prompt = flow.Prompt
var SystemPrompt = flow.SystemPrompt
var Provider = flow.Provider
var APIKey = flow.APIKey
var Model = flow.Model
var BaseURL = flow.BaseURL
var HistoryLimit = flow.HistoryLimit
var OnResult = flow.OnResult
+226
View File
@@ -0,0 +1,226 @@
// Package gemini implements the Google Gemini model provider.
//
// Usage:
//
// import _ "go-micro.dev/v6/ai/gemini"
//
// m := ai.New("gemini",
// ai.WithAPIKey("your-api-key"),
// )
package gemini
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"go-micro.dev/v6/ai"
)
func init() {
ai.Register("gemini", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
}
// Provider implements the ai.Model interface for Google Gemini.
type Provider struct {
opts ai.Options
}
// NewProvider creates a new Gemini provider.
func NewProvider(opts ...ai.Option) *Provider {
options := ai.NewOptions(opts...)
if options.Model == "" {
options.Model = "gemini-2.5-flash"
}
if options.BaseURL == "" {
options.BaseURL = "https://generativelanguage.googleapis.com"
}
return &Provider{opts: options}
}
func (p *Provider) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&p.opts)
}
return nil
}
func (p *Provider) Options() ai.Options { return p.opts }
func (p *Provider) String() string { return "gemini" }
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
var tools []map[string]any
for _, t := range req.Tools {
tools = append(tools, map[string]any{
"name": t.Name,
"description": t.Description,
"parameters": map[string]any{
"type": "object",
"properties": t.Properties,
},
})
}
contents := []map[string]any{
{"role": "user", "parts": []map[string]any{{"text": req.Prompt}}},
}
apiReq := map[string]any{
"contents": contents,
}
if req.SystemPrompt != "" {
apiReq["system_instruction"] = map[string]any{
"parts": []map[string]any{{"text": req.SystemPrompt}},
}
}
if len(tools) > 0 {
apiReq["tools"] = []map[string]any{
{"functionDeclarations": tools},
}
}
resp, rawParts, err := p.callAPI(ctx, apiReq)
if err != nil {
return nil, err
}
if len(resp.ToolCalls) == 0 {
return resp, nil
}
if p.opts.ToolHandler != nil {
var resultParts []map[string]any
for _, tc := range resp.ToolCalls {
result := p.opts.ToolHandler(ctx, tc).Value
resultParts = append(resultParts, map[string]any{
"functionResponse": map[string]any{
"name": tc.Name,
"id": tc.ID,
"response": result,
},
})
}
followUpContents := append(contents,
map[string]any{"role": "model", "parts": rawParts},
map[string]any{"role": "user", "parts": resultParts},
)
followUpReq := map[string]any{
"contents": followUpContents,
}
if req.SystemPrompt != "" {
followUpReq["system_instruction"] = map[string]any{
"parts": []map[string]any{{"text": req.SystemPrompt}},
}
}
followUpResp, _, err := p.callAPI(ctx, followUpReq)
if err == nil && followUpResp.Reply != "" {
resp.Answer = followUpResp.Reply
}
}
return resp, nil
}
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("streaming not yet implemented for gemini provider")
}
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, []map[string]any, error) {
reqBody, err := json.Marshal(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") +
"/v1beta/models/" + p.opts.Model + ":generateContent"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("x-goog-api-key", p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var geminiResp struct {
Candidates []struct {
Content struct {
Parts []struct {
Text string `json:"text"`
FunctionCall *functionCallPB `json:"functionCall"`
} `json:"parts"`
} `json:"content"`
} `json:"candidates"`
}
if err := json.Unmarshal(respBody, &geminiResp); err != nil {
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(geminiResp.Candidates) == 0 {
return nil, nil, fmt.Errorf("no response from API")
}
parts := geminiResp.Candidates[0].Content.Parts
response := &ai.Response{}
var replyParts []string
var rawParts []map[string]any
for _, part := range parts {
if part.Text != "" {
replyParts = append(replyParts, part.Text)
rawParts = append(rawParts, map[string]any{"text": part.Text})
}
if part.FunctionCall != nil {
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
ID: part.FunctionCall.ID,
Name: part.FunctionCall.Name,
Input: part.FunctionCall.Args,
})
rawParts = append(rawParts, map[string]any{
"functionCall": map[string]any{
"id": part.FunctionCall.ID,
"name": part.FunctionCall.Name,
"args": part.FunctionCall.Args,
},
})
}
}
if len(replyParts) > 0 {
response.Reply = strings.Join(replyParts, "\n")
}
return response, rawParts, nil
}
type functionCallPB struct {
ID string `json:"id"`
Name string `json:"name"`
Args map[string]any `json:"args"`
}
+104
View File
@@ -0,0 +1,104 @@
package gemini
import (
"context"
"testing"
"go-micro.dev/v6/ai"
)
func TestProvider_String(t *testing.T) {
p := NewProvider()
if p.String() != "gemini" {
t.Errorf("Expected provider name 'gemini', got '%s'", p.String())
}
}
func TestProvider_Init(t *testing.T) {
p := NewProvider()
err := p.Init(
ai.WithModel("gemini-2.0-flash"),
ai.WithAPIKey("test-key"),
ai.WithBaseURL("https://test.com"),
)
if err != nil {
t.Fatalf("Init failed: %v", err)
}
opts := p.Options()
if opts.Model != "gemini-2.0-flash" {
t.Errorf("Expected model 'gemini-2.0-flash', got '%s'", opts.Model)
}
if opts.APIKey != "test-key" {
t.Errorf("Expected API key 'test-key', got '%s'", opts.APIKey)
}
if opts.BaseURL != "https://test.com" {
t.Errorf("Expected base URL 'https://test.com', got '%s'", opts.BaseURL)
}
}
func TestProvider_Options(t *testing.T) {
p := NewProvider(
ai.WithModel("custom-model"),
ai.WithAPIKey("my-key"),
)
opts := p.Options()
if opts.Model != "custom-model" {
t.Errorf("Expected model 'custom-model', got '%s'", opts.Model)
}
if opts.APIKey != "my-key" {
t.Errorf("Expected API key 'my-key', got '%s'", opts.APIKey)
}
}
func TestProvider_Defaults(t *testing.T) {
p := NewProvider()
opts := p.Options()
if opts.Model != "gemini-2.5-flash" {
t.Errorf("Expected default model 'gemini-2.5-flash', got '%s'", opts.Model)
}
if opts.BaseURL != "https://generativelanguage.googleapis.com" {
t.Errorf("Expected default base URL 'https://generativelanguage.googleapis.com', got '%s'", opts.BaseURL)
}
}
func TestProvider_Generate_NoAPIKey(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
SystemPrompt: "You are helpful",
}
_, err := p.Generate(context.Background(), req)
if err == nil {
t.Error("Expected error when API key is missing, got nil")
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
}
_, err := p.Stream(context.Background(), req)
if err == nil {
t.Error("Expected error for unimplemented streaming, got nil")
}
}
func TestProvider_Registration(t *testing.T) {
m := ai.New("gemini", ai.WithAPIKey("test"))
if m == nil {
t.Fatal("ai.New('gemini') returned nil — provider not registered")
}
if m.String() != "gemini" {
t.Errorf("Expected 'gemini', got '%s'", m.String())
}
}
+194
View File
@@ -0,0 +1,194 @@
// Package groq implements the Groq model provider.
//
// Groq provides ultra-fast inference for open-weight models via an
// OpenAI-compatible chat completions endpoint.
//
// Usage:
//
// import _ "go-micro.dev/v6/ai/groq"
//
// m := ai.New("groq",
// ai.WithAPIKey("your-api-key"),
// )
package groq
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"go-micro.dev/v6/ai"
)
func init() {
ai.Register("groq", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
}
type Provider struct {
opts ai.Options
}
func NewProvider(opts ...ai.Option) *Provider {
options := ai.NewOptions(opts...)
if options.Model == "" {
options.Model = "llama-3.3-70b-versatile"
}
if options.BaseURL == "" {
options.BaseURL = "https://api.groq.com/openai"
}
return &Provider{opts: options}
}
func (p *Provider) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&p.opts)
}
return nil
}
func (p *Provider) Options() ai.Options { return p.opts }
func (p *Provider) String() string { return "groq" }
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
var tools []map[string]any
for _, t := range req.Tools {
tools = append(tools, map[string]any{
"type": "function",
"function": map[string]any{
"name": t.Name,
"description": t.Description,
"parameters": map[string]any{
"type": "object",
"properties": t.Properties,
},
},
})
}
messages := []map[string]any{
{"role": "system", "content": req.SystemPrompt},
{"role": "user", "content": req.Prompt},
}
apiReq := map[string]any{
"model": p.opts.Model,
"messages": messages,
}
if len(tools) > 0 {
apiReq["tools"] = tools
}
resp, rawMessage, err := p.callAPI(ctx, apiReq)
if err != nil {
return nil, err
}
if len(resp.ToolCalls) == 0 {
return resp, nil
}
if p.opts.ToolHandler != nil {
followUpMessages := append(messages, map[string]any{
"role": "assistant",
"content": rawMessage["content"],
"tool_calls": rawMessage["tool_calls"],
})
for _, tc := range resp.ToolCalls {
content := p.opts.ToolHandler(ctx, tc).Content
followUpMessages = append(followUpMessages, map[string]any{
"role": "tool",
"tool_call_id": tc.ID,
"content": content,
})
}
followUpResp, _, err := p.callAPI(ctx, map[string]any{
"model": p.opts.Model,
"messages": followUpMessages,
})
if err == nil && followUpResp.Reply != "" {
resp.Answer = followUpResp.Reply
}
}
return resp, nil
}
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("streaming not yet implemented for groq provider")
}
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, map[string]any, error) {
reqBody, err := json.Marshal(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/chat/completions"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var chatResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ToolCalls []struct {
ID string `json:"id"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
} `json:"tool_calls"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &chatResp); err != nil {
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(chatResp.Choices) == 0 {
return nil, nil, fmt.Errorf("no response from API")
}
choice := chatResp.Choices[0]
response := &ai.Response{Reply: choice.Message.Content}
for _, tc := range choice.Message.ToolCalls {
var input map[string]any
if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
input = map[string]any{}
}
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
ID: tc.ID,
Name: tc.Function.Name,
Input: input,
})
}
rawMessage := map[string]any{
"content": choice.Message.Content,
"tool_calls": choice.Message.ToolCalls,
}
return response, rawMessage, nil
}
+56
View File
@@ -0,0 +1,56 @@
package groq
import (
"context"
"testing"
"go-micro.dev/v6/ai"
)
func TestProvider_String(t *testing.T) {
if NewProvider().String() != "groq" {
t.Errorf("got %q", NewProvider().String())
}
}
func TestProvider_Defaults(t *testing.T) {
opts := NewProvider().Options()
if opts.Model != "llama-3.3-70b-versatile" {
t.Errorf("default model = %q", opts.Model)
}
if opts.BaseURL != "https://api.groq.com/openai" {
t.Errorf("default base URL = %q", opts.BaseURL)
}
}
func TestProvider_Init(t *testing.T) {
p := NewProvider()
if err := p.Init(ai.WithModel("m"), ai.WithAPIKey("k")); err != nil {
t.Fatal(err)
}
if p.Options().Model != "m" || p.Options().APIKey != "k" {
t.Error("Init did not apply options")
}
}
func TestProvider_Generate_NoAPIKey(t *testing.T) {
if _, err := NewProvider().Generate(context.Background(), &ai.Request{Prompt: "hi"}); err == nil {
t.Error("expected error without API key")
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
if _, err := NewProvider().Stream(context.Background(), &ai.Request{Prompt: "hi"}); err == nil {
t.Error("expected error")
}
}
func TestProvider_Registration(t *testing.T) {
m := ai.New("groq", ai.WithAPIKey("test"))
if m == nil {
t.Fatal("provider not registered")
}
if m.String() != "groq" {
t.Errorf("got %q", m.String())
}
}
+45
View File
@@ -0,0 +1,45 @@
package ai
// History is a convenience for accumulating conversation messages
// with automatic truncation. Use it to build Request.Messages for
// multi-turn conversations.
//
// hist := ai.NewHistory(50)
// hist.Add("user", "hello")
// resp, _ := m.Generate(ctx, &ai.Request{Messages: hist.Messages(), Prompt: "next"})
// hist.Add("assistant", resp.Reply)
type History struct {
messages []Message
limit int
}
// NewHistory creates an empty History. limit controls the maximum
// number of messages retained (0 = unlimited).
func NewHistory(limit int) *History {
return &History{limit: limit}
}
// Add appends a message and truncates if over limit.
func (h *History) Add(role string, content any) {
h.messages = append(h.messages, Message{Role: role, Content: content})
if h.limit > 0 && len(h.messages) > h.limit {
h.messages = h.messages[len(h.messages)-h.limit:]
}
}
// Messages returns a copy of the accumulated messages.
func (h *History) Messages() []Message {
out := make([]Message, len(h.messages))
copy(out, h.messages)
return out
}
// Len returns the number of messages.
func (h *History) Len() int {
return len(h.messages)
}
// Reset clears all messages.
func (h *History) Reset() {
h.messages = nil
}
+62
View File
@@ -0,0 +1,62 @@
package ai
import "testing"
func TestHistory_Add(t *testing.T) {
h := NewHistory(0)
h.Add("user", "hello")
h.Add("assistant", "hi")
if h.Len() != 2 {
t.Errorf("len = %d, want 2", h.Len())
}
msgs := h.Messages()
if msgs[0].Role != "user" || msgs[0].Content != "hello" {
t.Errorf("first = %+v", msgs[0])
}
if msgs[1].Role != "assistant" || msgs[1].Content != "hi" {
t.Errorf("second = %+v", msgs[1])
}
}
func TestHistory_Truncation(t *testing.T) {
h := NewHistory(3)
for _, m := range []string{"a", "b", "c", "d", "e"} {
h.Add("user", m)
}
if h.Len() != 3 {
t.Errorf("len = %d, want 3", h.Len())
}
if h.Messages()[0].Content != "c" {
t.Errorf("first retained = %+v", h.Messages()[0])
}
}
func TestHistory_Reset(t *testing.T) {
h := NewHistory(0)
h.Add("user", "hello")
h.Reset()
if h.Len() != 0 {
t.Errorf("len after reset = %d", h.Len())
}
}
func TestHistory_SnapshotIsCopy(t *testing.T) {
h := NewHistory(0)
h.Add("user", "hello")
msgs := h.Messages()
msgs[0].Content = "mutated"
if h.Messages()[0].Content == "mutated" {
t.Error("snapshot returned reference, not copy")
}
}
func TestHistory_Unlimited(t *testing.T) {
h := NewHistory(0)
for i := 0; i < 100; i++ {
h.Add("user", "msg")
}
if h.Len() != 100 {
t.Errorf("len = %d, want 100", h.Len())
}
}
+65
View File
@@ -0,0 +1,65 @@
package ai
import "context"
// ImageModel provides an interface for image generation providers.
// Providers that support image generation implement this alongside
// or instead of Model. Use NewImage to construct, or type-assert
// a provider that implements both:
//
// p := atlascloud.NewProvider(ai.WithAPIKey(key))
// if ig, ok := p.(ai.ImageModel); ok {
// resp, _ := ig.GenerateImage(ctx, req)
// }
type ImageModel interface {
GenerateImage(ctx context.Context, req *ImageRequest, opts ...GenerateOption) (*ImageResponse, error)
String() string
}
// ImageRequest describes what image to generate.
type ImageRequest struct {
// Prompt is the text description of the image to generate.
Prompt string
// Model overrides the provider's default image model.
Model string
// Size of the generated image (e.g. "1024x1024"). Provider-specific.
Size string
// N is the number of images to generate. Defaults to 1.
N int
// Quality controls generation quality. Provider-specific (e.g. "low", "medium", "high").
Quality string
// OutputFormat sets the image format (e.g. "png", "jpeg"). Provider-specific.
OutputFormat string
}
// ImageResponse holds the generated images.
type ImageResponse struct {
Images []Image
}
// Image is a single generated image, returned as a URL, base64 data, or both
// depending on the provider and request options.
type Image struct {
// URL is a remote URL where the image can be fetched.
URL string
// Base64 is the base64-encoded image data.
Base64 string
}
// NewImageFunc creates a new ImageModel instance.
type NewImageFunc func(...Option) ImageModel
var imageProviders = make(map[string]NewImageFunc)
// RegisterImage registers an image generation provider.
func RegisterImage(name string, fn NewImageFunc) {
imageProviders[name] = fn
}
// NewImage creates a new ImageModel instance based on the provider name.
func NewImage(provider string, opts ...Option) ImageModel {
if fn, ok := imageProviders[provider]; ok {
return fn(opts...)
}
return nil
}
+194
View File
@@ -0,0 +1,194 @@
// Package mistral implements the Mistral AI model provider.
//
// Mistral AI is a European AI company offering high-performance models
// via an OpenAI-compatible chat completions endpoint.
//
// Usage:
//
// import _ "go-micro.dev/v6/ai/mistral"
//
// m := ai.New("mistral",
// ai.WithAPIKey("your-api-key"),
// )
package mistral
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"go-micro.dev/v6/ai"
)
func init() {
ai.Register("mistral", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
}
type Provider struct {
opts ai.Options
}
func NewProvider(opts ...ai.Option) *Provider {
options := ai.NewOptions(opts...)
if options.Model == "" {
options.Model = "mistral-large-latest"
}
if options.BaseURL == "" {
options.BaseURL = "https://api.mistral.ai"
}
return &Provider{opts: options}
}
func (p *Provider) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&p.opts)
}
return nil
}
func (p *Provider) Options() ai.Options { return p.opts }
func (p *Provider) String() string { return "mistral" }
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
var tools []map[string]any
for _, t := range req.Tools {
tools = append(tools, map[string]any{
"type": "function",
"function": map[string]any{
"name": t.Name,
"description": t.Description,
"parameters": map[string]any{
"type": "object",
"properties": t.Properties,
},
},
})
}
messages := []map[string]any{
{"role": "system", "content": req.SystemPrompt},
{"role": "user", "content": req.Prompt},
}
apiReq := map[string]any{
"model": p.opts.Model,
"messages": messages,
}
if len(tools) > 0 {
apiReq["tools"] = tools
}
resp, rawMessage, err := p.callAPI(ctx, apiReq)
if err != nil {
return nil, err
}
if len(resp.ToolCalls) == 0 {
return resp, nil
}
if p.opts.ToolHandler != nil {
followUpMessages := append(messages, map[string]any{
"role": "assistant",
"content": rawMessage["content"],
"tool_calls": rawMessage["tool_calls"],
})
for _, tc := range resp.ToolCalls {
content := p.opts.ToolHandler(ctx, tc).Content
followUpMessages = append(followUpMessages, map[string]any{
"role": "tool",
"tool_call_id": tc.ID,
"content": content,
})
}
followUpResp, _, err := p.callAPI(ctx, map[string]any{
"model": p.opts.Model,
"messages": followUpMessages,
})
if err == nil && followUpResp.Reply != "" {
resp.Answer = followUpResp.Reply
}
}
return resp, nil
}
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("streaming not yet implemented for mistral provider")
}
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, map[string]any, error) {
reqBody, err := json.Marshal(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/chat/completions"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var chatResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ToolCalls []struct {
ID string `json:"id"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
} `json:"tool_calls"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &chatResp); err != nil {
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(chatResp.Choices) == 0 {
return nil, nil, fmt.Errorf("no response from API")
}
choice := chatResp.Choices[0]
response := &ai.Response{Reply: choice.Message.Content}
for _, tc := range choice.Message.ToolCalls {
var input map[string]any
if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
input = map[string]any{}
}
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
ID: tc.ID,
Name: tc.Function.Name,
Input: input,
})
}
rawMessage := map[string]any{
"content": choice.Message.Content,
"tool_calls": choice.Message.ToolCalls,
}
return response, rawMessage, nil
}
+56
View File
@@ -0,0 +1,56 @@
package mistral
import (
"context"
"testing"
"go-micro.dev/v6/ai"
)
func TestProvider_String(t *testing.T) {
if NewProvider().String() != "mistral" {
t.Errorf("got %q", NewProvider().String())
}
}
func TestProvider_Defaults(t *testing.T) {
opts := NewProvider().Options()
if opts.Model != "mistral-large-latest" {
t.Errorf("default model = %q", opts.Model)
}
if opts.BaseURL != "https://api.mistral.ai" {
t.Errorf("default base URL = %q", opts.BaseURL)
}
}
func TestProvider_Init(t *testing.T) {
p := NewProvider()
if err := p.Init(ai.WithModel("m"), ai.WithAPIKey("k")); err != nil {
t.Fatal(err)
}
if p.Options().Model != "m" || p.Options().APIKey != "k" {
t.Error("Init did not apply options")
}
}
func TestProvider_Generate_NoAPIKey(t *testing.T) {
if _, err := NewProvider().Generate(context.Background(), &ai.Request{Prompt: "hi"}); err == nil {
t.Error("expected error without API key")
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
if _, err := NewProvider().Stream(context.Background(), &ai.Request{Prompt: "hi"}); err == nil {
t.Error("expected error")
}
}
func TestProvider_Registration(t *testing.T) {
m := ai.New("mistral", ai.WithAPIKey("test"))
if m == nil {
t.Fatal("provider not registered")
}
if m.String() != "mistral" {
t.Errorf("got %q", m.String())
}
}
+214
View File
@@ -0,0 +1,214 @@
// Package ai provides abstraction for AI model providers
package ai
import (
"context"
"encoding/json"
"strings"
)
// Model provides an interface for interacting with AI model providers
type Model interface {
// Init initializes the model with options
Init(...Option) error
// Options returns the model options
Options() Options
// Generate generates a response from the model
Generate(ctx context.Context, req *Request, opts ...GenerateOption) (*Response, error)
// Stream generates a streaming response (for future implementation)
Stream(ctx context.Context, req *Request, opts ...GenerateOption) (Stream, error)
// String returns the name of the provider
String() string
}
// Tool represents a tool/function that can be called by the model
type Tool struct {
Name string // LLM-safe name (e.g., "greeter_Greeter_Hello")
OriginalName string // Original name (e.g., "greeter.Greeter.Hello")
Description string
Properties map[string]any // JSON schema for tool parameters
}
// Request represents a request to generate content from a model
type Request struct {
// Prompt is the user's message/prompt
Prompt string
// SystemPrompt is the system instruction for the model
SystemPrompt string
// Tools available for the model to use
Tools []Tool
// Messages for continuing a conversation (optional).
// Use ai.History to accumulate these across turns.
Messages []Message
}
// Message represents a conversation message
type Message struct {
Role string // "user", "assistant", "system", "tool"
Content any // Can be string or structured content
}
// Usage describes token counts returned by model providers.
type Usage struct {
InputTokens int `json:"input_tokens,omitempty"`
OutputTokens int `json:"output_tokens,omitempty"`
TotalTokens int `json:"total_tokens,omitempty"`
}
// Response represents the response from a model
type Response struct {
// Reply is the text response from the model
Reply string
// ToolCalls are tool calls requested by the model
ToolCalls []ToolCall
// Answer is the final answer after tool execution (if tools were used)
Answer string
// Usage contains provider token usage when available.
Usage Usage
}
// ToolCall represents a request to call a tool and its result
type ToolCall struct {
ID string // Tool call ID (for correlation)
Name string // Tool name
Input map[string]any // Tool input arguments
Result string // Tool execution result (populated after execution)
Error string // Tool execution error (populated after execution)
}
// Scan decodes the call's Input into v (a pointer to a struct or map),
// the same way a codec decodes an RPC request body. Use it when a tool
// wants typed arguments instead of the raw map:
//
// var args struct{ Query string `json:"query"` }
// if err := call.Scan(&args); err != nil { ... }
func (c ToolCall) Scan(v any) error {
b, err := json.Marshal(c.Input)
if err != nil {
return err
}
return json.Unmarshal(b, v)
}
// ToolResult represents the result of a tool execution
type ToolResult struct {
ID string // Tool call ID (for correlation)
Value any // Structured result (optional)
Content string // Tool execution result (JSON string), shown to the model
// Refused names the reason a guardrail blocked the call before it ran
// ("max_steps", "loop", "approval"); empty when the call executed. A
// tool wrapper can switch on it to build reliability tooling — react to
// a detected loop, audit refusals — without parsing the message.
Refused string `json:"refused,omitempty"`
}
// Refusal reason codes set on ToolResult.Refused by the agent's guardrails.
const (
RefusedMaxSteps = "max_steps"
RefusedLoop = "loop"
RefusedApproval = "approval"
)
// RunInfo describes the agent run a tool call belongs to. The agent
// attaches it to the context passed to a ToolHandler, so a wrapper can
// correlate calls within a run and across delegation without coupling to
// the agent package. Per-call detail (tool name, id) is on the ToolCall;
// step and attempt counts are naturally counted by the wrapper itself.
type RunInfo struct {
RunID string // correlation id for this agent run (one per Ask)
ParentID string // the run that delegated to this one, if any
Agent string // the agent's name
}
type runInfoKey struct{}
// WithRunInfo attaches run info to ctx.
func WithRunInfo(ctx context.Context, r RunInfo) context.Context {
return context.WithValue(ctx, runInfoKey{}, r)
}
// RunInfoFrom returns the run info attached to ctx, and whether it was set.
func RunInfoFrom(ctx context.Context) (RunInfo, bool) {
r, ok := ctx.Value(runInfoKey{}).(RunInfo)
return r, ok
}
// Stream is the interface for streaming responses (future implementation)
type Stream interface {
// Recv receives the next chunk of the response
Recv() (*Response, error)
// Close closes the stream
Close() error
}
// ToolHandler executes a tool call and returns its result. It mirrors a
// go-micro RPC handler — context first, a request in, a result out — so
// the same mental model carries over from services to tools.
type ToolHandler func(ctx context.Context, call ToolCall) ToolResult
// ToolWrapper wraps a ToolHandler to add behavior around execution —
// logging, metrics, retries, guardrails. It is the tool-side analog of
// client.CallWrapper and server.HandlerWrapper: a wrapper takes the next
// handler and returns a new one, and code before the next(...) call runs
// before the tool, code after runs after.
type ToolWrapper func(ToolHandler) ToolHandler
// NewFunc creates a new Model instance
type NewFunc func(...Option) Model
var providers = make(map[string]NewFunc)
// Register registers a model provider
func Register(name string, fn NewFunc) {
providers[name] = fn
}
// New creates a new Model instance based on the provider name
func New(provider string, opts ...Option) Model {
if fn, ok := providers[provider]; ok {
return fn(opts...)
}
// Default to first registered provider
if len(providers) > 0 {
for _, fn := range providers {
return fn(opts...)
}
}
return nil
}
// AutoDetectProvider attempts to detect the provider from the base URL
func AutoDetectProvider(baseURL string) string {
if baseURL == "" {
return "openai"
}
switch {
case strings.Contains(baseURL, "anthropic"):
return "anthropic"
case strings.Contains(baseURL, "atlascloud"):
return "atlascloud"
case strings.Contains(baseURL, "googleapis.com"), strings.Contains(baseURL, "google"):
return "gemini"
case strings.Contains(baseURL, "groq"):
return "groq"
case strings.Contains(baseURL, "mistral"):
return "mistral"
case strings.Contains(baseURL, "together"):
return "together"
default:
return "openai"
}
}
// DefaultModel is a default model instance
var DefaultModel Model
// Generate generates a response using the default model.
func Generate(ctx context.Context, req *Request, opts ...GenerateOption) (*Response, error) {
if DefaultModel == nil {
return nil, nil
}
return DefaultModel.Generate(ctx, req, opts...)
}
+303
View File
@@ -0,0 +1,303 @@
// Package openai implements the OpenAI model provider
package openai
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"go-micro.dev/v6/ai"
)
func init() {
ai.Register("openai", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
ai.RegisterImage("openai", func(opts ...ai.Option) ai.ImageModel {
return NewProvider(opts...)
})
}
// Provider implements the ai.Model interface for OpenAI
type Provider struct {
opts ai.Options
}
// NewProvider creates a new OpenAI provider
func NewProvider(opts ...ai.Option) *Provider {
options := ai.NewOptions(opts...)
// Set defaults if not provided
if options.Model == "" {
options.Model = "gpt-4o"
}
if options.BaseURL == "" {
options.BaseURL = "https://api.openai.com"
}
return &Provider{
opts: options,
}
}
// Init initializes the provider with options
func (p *Provider) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&p.opts)
}
return nil
}
// Options returns the provider options
func (p *Provider) Options() ai.Options {
return p.opts
}
// String returns the provider name
func (p *Provider) String() string {
return "openai"
}
// Generate generates a response from the model
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
// Build tools for OpenAI format
var openaiTools []map[string]any
for _, t := range req.Tools {
openaiTools = append(openaiTools, map[string]any{
"type": "function",
"function": map[string]any{
"name": t.Name,
"description": t.Description,
"parameters": map[string]any{
"type": "object",
"properties": t.Properties,
},
},
})
}
// Build messages
messages := []map[string]any{
{"role": "system", "content": req.SystemPrompt},
{"role": "user", "content": req.Prompt},
}
// Build initial request
apiReq := map[string]any{
"model": p.opts.Model,
"messages": messages,
}
if len(openaiTools) > 0 {
apiReq["tools"] = openaiTools
}
// Make API call
resp, rawMessage, err := p.callAPI(ctx, apiReq)
if err != nil {
return nil, err
}
// If no tool calls, return response
if len(resp.ToolCalls) == 0 {
return resp, nil
}
// If tool handler is provided, execute tools and get final answer
if p.opts.ToolHandler != nil {
// Build follow-up messages
followUpMessages := append(messages, map[string]any{
"role": "assistant",
"content": rawMessage["content"],
"tool_calls": rawMessage["tool_calls"],
})
for _, tc := range resp.ToolCalls {
content := p.opts.ToolHandler(ctx, tc).Content
followUpMessages = append(followUpMessages, map[string]any{
"role": "tool",
"tool_call_id": tc.ID,
"content": content,
})
}
followUpReq := map[string]any{
"model": p.opts.Model,
"messages": followUpMessages,
}
// Make follow-up API call
followUpResp, _, err := p.callAPI(ctx, followUpReq)
if err == nil && followUpResp.Reply != "" {
resp.Answer = followUpResp.Reply
}
}
return resp, nil
}
// Stream generates a streaming response (not yet implemented)
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("streaming not yet implemented for openai provider")
}
// callAPI makes an HTTP request to the OpenAI API
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, map[string]any, error) {
// Marshal request
reqBody, err := json.Marshal(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
// Build HTTP request
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/chat/completions"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
// Set headers
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
// Make request
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
// Read response
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
// Parse response
var chatResp struct {
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
Choices []struct {
Message struct {
Content string `json:"content"`
ToolCalls []struct {
ID string `json:"id"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
} `json:"tool_calls"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &chatResp); err != nil {
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(chatResp.Choices) == 0 {
return nil, nil, fmt.Errorf("no response from API")
}
choice := chatResp.Choices[0]
response := &ai.Response{
Reply: choice.Message.Content,
Usage: ai.Usage{InputTokens: chatResp.Usage.PromptTokens, OutputTokens: chatResp.Usage.CompletionTokens, TotalTokens: chatResp.Usage.TotalTokens},
}
// Extract tool calls
for _, tc := range choice.Message.ToolCalls {
var input map[string]any
if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
input = map[string]any{}
}
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
ID: tc.ID,
Name: tc.Function.Name,
Input: input,
})
}
// Return raw message for potential follow-up
rawMessage := map[string]any{
"content": choice.Message.Content,
"tool_calls": choice.Message.ToolCalls,
}
return response, rawMessage, nil
}
const defaultImageModel = "gpt-image-1"
func (p *Provider) GenerateImage(ctx context.Context, req *ai.ImageRequest, opts ...ai.GenerateOption) (*ai.ImageResponse, error) {
model := req.Model
if model == "" {
model = defaultImageModel
}
n := req.N
if n <= 0 {
n = 1
}
apiReq := map[string]any{
"model": model,
"prompt": req.Prompt,
"n": n,
}
if req.Size != "" {
apiReq["size"] = req.Size
}
reqBody, err := json.Marshal(apiReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/images/generations"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var imgResp struct {
Data []struct {
URL string `json:"url"`
B64JSON string `json:"b64_json"`
} `json:"data"`
}
if err := json.Unmarshal(respBody, &imgResp); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
response := &ai.ImageResponse{}
for _, d := range imgResp.Data {
response.Images = append(response.Images, ai.Image{
URL: d.URL,
Base64: d.B64JSON,
})
}
return response, nil
}
+116
View File
@@ -0,0 +1,116 @@
package openai
import (
"context"
"testing"
"go-micro.dev/v6/ai"
)
func TestProvider_String(t *testing.T) {
p := NewProvider()
if p.String() != "openai" {
t.Errorf("Expected provider name 'openai', got '%s'", p.String())
}
}
func TestProvider_Init(t *testing.T) {
p := NewProvider()
err := p.Init(
ai.WithModel("test-model"),
ai.WithAPIKey("test-key"),
ai.WithBaseURL("https://test.com"),
)
if err != nil {
t.Fatalf("Init failed: %v", err)
}
opts := p.Options()
if opts.Model != "test-model" {
t.Errorf("Expected model 'test-model', got '%s'", opts.Model)
}
if opts.APIKey != "test-key" {
t.Errorf("Expected API key 'test-key', got '%s'", opts.APIKey)
}
if opts.BaseURL != "https://test.com" {
t.Errorf("Expected base URL 'https://test.com', got '%s'", opts.BaseURL)
}
}
func TestProvider_Options(t *testing.T) {
p := NewProvider(
ai.WithModel("custom-model"),
ai.WithAPIKey("my-key"),
)
opts := p.Options()
if opts.Model != "custom-model" {
t.Errorf("Expected model 'custom-model', got '%s'", opts.Model)
}
if opts.APIKey != "my-key" {
t.Errorf("Expected API key 'my-key', got '%s'", opts.APIKey)
}
}
func TestProvider_Defaults(t *testing.T) {
p := NewProvider()
opts := p.Options()
if opts.Model != "gpt-4o" {
t.Errorf("Expected default model 'gpt-4o', got '%s'", opts.Model)
}
if opts.BaseURL != "https://api.openai.com" {
t.Errorf("Expected default base URL 'https://api.openai.com', got '%s'", opts.BaseURL)
}
}
func TestProvider_Generate_NoAPIKey(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
SystemPrompt: "You are helpful",
}
_, err := p.Generate(context.Background(), req)
if err == nil {
t.Error("Expected error when API key is missing, got nil")
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
p := NewProvider()
req := &ai.Request{
Prompt: "Hello",
}
_, err := p.Stream(context.Background(), req)
if err == nil {
t.Error("Expected error for unimplemented streaming, got nil")
}
}
func TestProvider_ImageRegistration(t *testing.T) {
ig := ai.NewImage("openai", ai.WithAPIKey("test"))
if ig == nil {
t.Fatal("ai.NewImage('openai') returned nil — image provider not registered")
}
if ig.String() != "openai" {
t.Errorf("Expected 'openai', got '%s'", ig.String())
}
}
func TestProvider_GenerateImage_NoAPIKey(t *testing.T) {
p := NewProvider()
_, err := p.GenerateImage(context.Background(), &ai.ImageRequest{Prompt: "a cat"})
if err == nil {
t.Error("Expected error when API key is missing, got nil")
}
}
func TestProvider_ImplementsImageModel(t *testing.T) {
var _ ai.ImageModel = (*Provider)(nil)
}
+93
View File
@@ -0,0 +1,93 @@
package ai
import (
"context"
)
// Options for model configuration
type Options struct {
// Context for the model
Context context.Context
// Model name (e.g., "gpt-4o", "claude-sonnet-4-20250514")
Model string
// APIKey for authentication
APIKey string
// BaseURL for the API endpoint
BaseURL string
// ToolHandler handles tool calls (optional, for automatic tool execution)
ToolHandler ToolHandler
}
// GenerateOptions for generate call
type GenerateOptions struct {
// Context for this specific generate call
Context context.Context
}
// Option is a function that modifies Options
type Option func(*Options)
// GenerateOption is a function that modifies GenerateOptions
type GenerateOption func(*GenerateOptions)
// NewOptions creates new Options with defaults
func NewOptions(opts ...Option) Options {
options := Options{
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
return options
}
// WithModel sets the model name
func WithModel(m string) Option {
return func(o *Options) {
o.Model = m
}
}
// WithAPIKey sets the API key
func WithAPIKey(key string) Option {
return func(o *Options) {
o.APIKey = key
}
}
// WithBaseURL sets the base URL
func WithBaseURL(url string) Option {
return func(o *Options) {
o.BaseURL = url
}
}
// WithContext sets the context
func WithContext(ctx context.Context) Option {
return func(o *Options) {
o.Context = ctx
}
}
// WithToolHandler sets the tool handler
func WithToolHandler(handler ToolHandler) Option {
return func(o *Options) {
o.ToolHandler = handler
}
}
// WithTools wires a Tools instance into the model, setting the tool
// handler so the model can execute discovered service endpoints. The
// tool list itself is passed per-request via Request.Tools.
//
// tools := ai.NewTools(service.Registry())
// list, _ := tools.Discover()
// m := ai.New("anthropic", ai.WithAPIKey(key), ai.WithTools(tools))
// resp, _ := m.Generate(ctx, &ai.Request{Prompt: input, Tools: list})
func WithTools(t *Tools) Option {
return func(o *Options) {
if t != nil {
o.ToolHandler = t.Handler()
}
}
}
+125
View File
@@ -0,0 +1,125 @@
package ai
import (
"context"
"errors"
"fmt"
"strings"
"time"
)
// StatusCoder is implemented by provider errors that expose an HTTP-like status code.
type StatusCoder interface {
StatusCode() int
}
// RetryError is returned when Generate is retried and still fails.
type RetryError struct {
Attempts int
Err error
}
func (e *RetryError) Error() string {
if e == nil {
return ""
}
return fmt.Sprintf("ai generate failed after %d attempt(s): %v", e.Attempts, e.Err)
}
func (e *RetryError) Unwrap() error {
if e == nil {
return nil
}
return e.Err
}
// GeneratePolicy controls timeout and retry behavior for a model call.
type GeneratePolicy struct {
Timeout time.Duration
MaxAttempts int
Backoff time.Duration
}
// GenerateWithRetry calls m.Generate with per-attempt timeout and bounded retry.
func GenerateWithRetry(ctx context.Context, m Model, req *Request, policy GeneratePolicy, opts ...GenerateOption) (*Response, error) {
if policy.MaxAttempts <= 0 {
policy.MaxAttempts = 1
}
if m == nil {
return nil, errors.New("ai model is nil")
}
var last error
for attempt := 1; attempt <= policy.MaxAttempts; attempt++ {
if err := ctx.Err(); err != nil {
return nil, err
}
callCtx := ctx
cancel := func() {}
if policy.Timeout > 0 {
callCtx, cancel = context.WithTimeout(ctx, policy.Timeout)
}
resp, err := m.Generate(callCtx, req, opts...)
cancel()
if err == nil {
return resp, nil
}
last = err
// Caller cancellation/deadline always wins and is not retried.
if ctx.Err() != nil {
return nil, ctx.Err()
}
if attempt == policy.MaxAttempts || !IsTransientError(err) {
if attempt > 1 || IsTransientError(err) {
return nil, &RetryError{Attempts: attempt, Err: err}
}
return nil, err
}
// Always back off between retries — exponential and capped — so an
// opt-in retry can never become a tight loop hammering the provider,
// even if Backoff was left at zero.
backoff := policy.Backoff
if backoff <= 0 {
backoff = 200 * time.Millisecond
}
if shift := attempt - 1; shift > 0 {
backoff <<= shift
}
if backoff > 30*time.Second {
backoff = 30 * time.Second
}
t := time.NewTimer(backoff)
select {
case <-ctx.Done():
if !t.Stop() {
<-t.C
}
return nil, ctx.Err()
case <-t.C:
}
}
return nil, &RetryError{Attempts: policy.MaxAttempts, Err: last}
}
// IsTransientError reports whether err is worth retrying at the provider boundary.
func IsTransientError(err error) bool {
if err == nil {
return false
}
if errors.Is(err, context.Canceled) {
return false
}
if errors.Is(err, context.DeadlineExceeded) {
return true
}
var sc StatusCoder
if errors.As(err, &sc) {
code := sc.StatusCode()
return code == 429 || code >= 500
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "rate limit") || strings.Contains(msg, "too many requests") || strings.Contains(msg, "timeout") || strings.Contains(msg, "temporar")
}
+194
View File
@@ -0,0 +1,194 @@
// Package together implements the Together AI model provider.
//
// Together AI provides fast inference for open-weight models via an
// OpenAI-compatible chat completions endpoint.
//
// Usage:
//
// import _ "go-micro.dev/v6/ai/together"
//
// m := ai.New("together",
// ai.WithAPIKey("your-api-key"),
// )
package together
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"go-micro.dev/v6/ai"
)
func init() {
ai.Register("together", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
}
type Provider struct {
opts ai.Options
}
func NewProvider(opts ...ai.Option) *Provider {
options := ai.NewOptions(opts...)
if options.Model == "" {
options.Model = "meta-llama/Llama-3.3-70B-Instruct-Turbo"
}
if options.BaseURL == "" {
options.BaseURL = "https://api.together.xyz"
}
return &Provider{opts: options}
}
func (p *Provider) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&p.opts)
}
return nil
}
func (p *Provider) Options() ai.Options { return p.opts }
func (p *Provider) String() string { return "together" }
func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (*ai.Response, error) {
var tools []map[string]any
for _, t := range req.Tools {
tools = append(tools, map[string]any{
"type": "function",
"function": map[string]any{
"name": t.Name,
"description": t.Description,
"parameters": map[string]any{
"type": "object",
"properties": t.Properties,
},
},
})
}
messages := []map[string]any{
{"role": "system", "content": req.SystemPrompt},
{"role": "user", "content": req.Prompt},
}
apiReq := map[string]any{
"model": p.opts.Model,
"messages": messages,
}
if len(tools) > 0 {
apiReq["tools"] = tools
}
resp, rawMessage, err := p.callAPI(ctx, apiReq)
if err != nil {
return nil, err
}
if len(resp.ToolCalls) == 0 {
return resp, nil
}
if p.opts.ToolHandler != nil {
followUpMessages := append(messages, map[string]any{
"role": "assistant",
"content": rawMessage["content"],
"tool_calls": rawMessage["tool_calls"],
})
for _, tc := range resp.ToolCalls {
content := p.opts.ToolHandler(ctx, tc).Content
followUpMessages = append(followUpMessages, map[string]any{
"role": "tool",
"tool_call_id": tc.ID,
"content": content,
})
}
followUpResp, _, err := p.callAPI(ctx, map[string]any{
"model": p.opts.Model,
"messages": followUpMessages,
})
if err == nil && followUpResp.Reply != "" {
resp.Answer = followUpResp.Reply
}
}
return resp, nil
}
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("streaming not yet implemented for together provider")
}
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, map[string]any, error) {
reqBody, err := json.Marshal(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to marshal request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") + "/v1/chat/completions"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, nil, fmt.Errorf("API request failed: %w", err)
}
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
if httpResp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("API error (%s): %s", httpResp.Status, string(respBody))
}
var chatResp struct {
Choices []struct {
Message struct {
Content string `json:"content"`
ToolCalls []struct {
ID string `json:"id"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
} `json:"tool_calls"`
} `json:"message"`
} `json:"choices"`
}
if err := json.Unmarshal(respBody, &chatResp); err != nil {
return nil, nil, fmt.Errorf("failed to parse response: %w", err)
}
if len(chatResp.Choices) == 0 {
return nil, nil, fmt.Errorf("no response from API")
}
choice := chatResp.Choices[0]
response := &ai.Response{Reply: choice.Message.Content}
for _, tc := range choice.Message.ToolCalls {
var input map[string]any
if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
input = map[string]any{}
}
response.ToolCalls = append(response.ToolCalls, ai.ToolCall{
ID: tc.ID,
Name: tc.Function.Name,
Input: input,
})
}
rawMessage := map[string]any{
"content": choice.Message.Content,
"tool_calls": choice.Message.ToolCalls,
}
return response, rawMessage, nil
}
+56
View File
@@ -0,0 +1,56 @@
package together
import (
"context"
"testing"
"go-micro.dev/v6/ai"
)
func TestProvider_String(t *testing.T) {
if NewProvider().String() != "together" {
t.Errorf("got %q", NewProvider().String())
}
}
func TestProvider_Defaults(t *testing.T) {
opts := NewProvider().Options()
if opts.Model != "meta-llama/Llama-3.3-70B-Instruct-Turbo" {
t.Errorf("default model = %q", opts.Model)
}
if opts.BaseURL != "https://api.together.xyz" {
t.Errorf("default base URL = %q", opts.BaseURL)
}
}
func TestProvider_Init(t *testing.T) {
p := NewProvider()
if err := p.Init(ai.WithModel("m"), ai.WithAPIKey("k")); err != nil {
t.Fatal(err)
}
if p.Options().Model != "m" || p.Options().APIKey != "k" {
t.Error("Init did not apply options")
}
}
func TestProvider_Generate_NoAPIKey(t *testing.T) {
if _, err := NewProvider().Generate(context.Background(), &ai.Request{Prompt: "hi"}); err == nil {
t.Error("expected error without API key")
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
if _, err := NewProvider().Stream(context.Background(), &ai.Request{Prompt: "hi"}); err == nil {
t.Error("expected error")
}
}
func TestProvider_Registration(t *testing.T) {
m := ai.New("together", ai.WithAPIKey("test"))
if m == nil {
t.Fatal("provider not registered")
}
if m.String() != "together" {
t.Errorf("got %q", m.String())
}
}
+185
View File
@@ -0,0 +1,185 @@
package ai
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"go-micro.dev/v6/client"
codecBytes "go-micro.dev/v6/codec/bytes"
"go-micro.dev/v6/registry"
)
type toolNameMap struct {
mu sync.RWMutex
m map[string]string
}
func (n *toolNameMap) put(safe, original string) {
n.mu.Lock()
n.m[safe] = original
n.mu.Unlock()
}
func (n *toolNameMap) get(safe string) (string, bool) {
n.mu.RLock()
v, ok := n.m[safe]
n.mu.RUnlock()
return v, ok
}
// Tools discovers go-micro services from a registry and converts their
// endpoints into Tool definitions. It also executes tool calls via RPC.
//
// Create with NewTools, discover the tool list with Discover, and wire
// execution into a model with WithTools:
//
// tools := ai.NewTools(service.Registry())
// list, _ := tools.Discover()
// m := ai.New("anthropic", ai.WithAPIKey(key), ai.WithTools(tools))
// resp, _ := m.Generate(ctx, &ai.Request{Prompt: input, Tools: list})
type Tools struct {
registry registry.Registry
client client.Client
names *toolNameMap
}
// ToolOption configures a Tools instance.
type ToolOption func(*Tools)
// ToolClient sets the client used to execute tool calls. Defaults to
// client.DefaultClient.
func ToolClient(c client.Client) ToolOption {
return func(t *Tools) {
if c != nil {
t.client = c
}
}
}
// NewTools creates a Tools bound to the given registry.
func NewTools(reg registry.Registry, opts ...ToolOption) *Tools {
t := &Tools{
registry: reg,
client: client.DefaultClient,
names: &toolNameMap{m: map[string]string{}},
}
for _, o := range opts {
o(t)
}
return t
}
// Discover walks the registry and returns one Tool per service
// endpoint. Tool names are LLM-safe (dots replaced with underscores).
func (t *Tools) Discover() ([]Tool, error) {
services, err := t.registry.ListServices()
if err != nil {
return nil, err
}
var out []Tool
for _, svc := range services {
full, err := t.registry.GetService(svc.Name)
if err != nil || len(full) == 0 {
continue
}
for _, ep := range full[0].Endpoints {
original := fmt.Sprintf("%s.%s", svc.Name, ep.Name)
safe := strings.ReplaceAll(original, ".", "_")
t.names.put(safe, original)
desc := fmt.Sprintf("Call %s on %s service", ep.Name, svc.Name)
if ep.Metadata != nil {
if d, ok := ep.Metadata["description"]; ok && d != "" {
desc = d
}
}
props := map[string]any{}
if ep.Request != nil {
for _, field := range ep.Request.Values {
props[field.Name] = map[string]any{
"type": toolJSONType(field.Type),
"description": fmt.Sprintf("%s (%s)", field.Name, field.Type),
}
}
}
out = append(out, Tool{
Name: safe,
OriginalName: original,
Description: desc,
Properties: props,
})
}
}
return out, nil
}
// Handler returns a ToolHandler that executes tool calls via RPC using
// the configured client. Tool names may be LLM-safe (underscored) or
// original (dotted). WithTools uses this internally.
func (t *Tools) Handler() ToolHandler {
c := t.client
if c == nil {
c = client.DefaultClient
}
return func(ctx context.Context, call ToolCall) ToolResult {
name := call.Name
if orig, ok := t.names.get(name); ok {
name = orig
}
parts := strings.SplitN(name, ".", 2)
if len(parts) != 2 {
return toolErrResult(call.ID, "invalid tool name: "+name)
}
inputBytes, err := json.Marshal(call.Input)
if err != nil {
return toolErrResult(call.ID, "failed to marshal input: "+err.Error())
}
req := c.NewRequest(parts[0], parts[1], &codecBytes.Frame{Data: inputBytes})
var rsp codecBytes.Frame
if err := c.Call(ctx, req, &rsp); err != nil {
return toolErrResult(call.ID, err.Error())
}
var result any
if err := json.Unmarshal(rsp.Data, &result); err != nil {
result = string(rsp.Data)
}
return ToolResult{ID: call.ID, Value: result, Content: string(rsp.Data)}
}
}
// DiscoverTools is a convenience that discovers tools from a registry
// without creating a Tools instance. For paired discovery + execution,
// create a Tools with NewTools instead.
func DiscoverTools(reg registry.Registry) ([]Tool, error) {
return NewTools(reg).Discover()
}
func toolErrResult(id, msg string) ToolResult {
encoded, _ := json.Marshal(map[string]string{"error": msg})
return ToolResult{ID: id, Value: map[string]string{"error": msg}, Content: string(encoded)}
}
func toolJSONType(goType string) string {
switch goType {
case "string":
return "string"
case "int", "int32", "int64", "uint", "uint32", "uint64":
return "integer"
case "float32", "float64":
return "number"
case "bool":
return "boolean"
default:
return "object"
}
}
+116
View File
@@ -0,0 +1,116 @@
package ai
import (
"context"
"testing"
"go-micro.dev/v6/registry"
)
func TestToolJSONType(t *testing.T) {
cases := map[string]string{
"string": "string",
"int": "integer",
"int64": "integer",
"float64": "number",
"bool": "boolean",
"User": "object",
"": "object",
}
for in, want := range cases {
if got := toolJSONType(in); got != want {
t.Errorf("toolJSONType(%q) = %q, want %q", in, got, want)
}
}
}
func TestDiscoverTools_Empty(t *testing.T) {
reg := registry.NewMemoryRegistry()
tools, err := DiscoverTools(reg)
if err != nil {
t.Fatalf("DiscoverTools: %v", err)
}
if len(tools) != 0 {
t.Errorf("expected 0 tools, got %d", len(tools))
}
}
func TestDiscoverTools_DiscoversEndpoints(t *testing.T) {
reg := registry.NewMemoryRegistry()
svc := &registry.Service{
Name: "users",
Version: "1.0.0",
Nodes: []*registry.Node{
{Id: "users-1", Address: "127.0.0.1:9000"},
},
Endpoints: []*registry.Endpoint{
{
Name: "Users.Get",
Metadata: map[string]string{
"description": "Fetch a user by ID",
},
Request: &registry.Value{
Name: "GetRequest",
Type: "GetRequest",
Values: []*registry.Value{
{Name: "id", Type: "string"},
{Name: "expand", Type: "bool"},
},
},
},
},
}
if err := reg.Register(svc); err != nil {
t.Fatalf("Register: %v", err)
}
tools, err := DiscoverTools(reg)
if err != nil {
t.Fatalf("DiscoverTools: %v", err)
}
if len(tools) != 1 {
t.Fatalf("expected 1 tool, got %d", len(tools))
}
tool := tools[0]
if tool.Name != "users_Users_Get" {
t.Errorf("safe name = %q", tool.Name)
}
if tool.OriginalName != "users.Users.Get" {
t.Errorf("original = %q", tool.OriginalName)
}
if tool.Description != "Fetch a user by ID" {
t.Errorf("description = %q", tool.Description)
}
}
func TestTools_HandlerResolvesSafeName(t *testing.T) {
tools := NewTools(registry.NewMemoryRegistry())
tools.names.put("users_Users_Get", "users.Users.Get")
resolved, ok := tools.names.get("users_Users_Get")
if !ok || resolved != "users.Users.Get" {
t.Errorf("name map lookup = (%q, %v)", resolved, ok)
}
}
func TestTools_HandlerInvalidName(t *testing.T) {
tools := NewTools(registry.NewMemoryRegistry())
h := tools.Handler()
res := h(context.Background(), ToolCall{Name: "foo", Input: map[string]any{}})
if res.Value == nil {
t.Fatal("expected error result")
}
if res.Content == "" {
t.Error("expected non-empty content")
}
}
func TestWithTools(t *testing.T) {
tools := NewTools(registry.NewMemoryRegistry())
opts := NewOptions(WithTools(tools))
if opts.ToolHandler == nil {
t.Error("WithTools did not set a ToolHandler")
}
}
+51
View File
@@ -0,0 +1,51 @@
package ai
import "context"
// VideoModel provides an interface for video generation providers.
// Providers that support video generation implement this alongside
// Model and/or ImageModel.
type VideoModel interface {
GenerateVideo(ctx context.Context, req *VideoRequest, opts ...GenerateOption) (*VideoResponse, error)
String() string
}
// VideoRequest describes what video to generate.
type VideoRequest struct {
// Prompt is the text description or instructions for the video.
Prompt string
// Model overrides the provider's default video model.
Model string
// Images are reference image URLs for image-to-video generation.
Images []string
// Duration in seconds. Provider-specific defaults apply.
Duration int
// AspectRatio (e.g. "16:9", "9:16"). Provider-specific.
AspectRatio string
// Resolution (e.g. "720p", "1080p"). Provider-specific.
Resolution string
}
// VideoResponse holds the generated video.
type VideoResponse struct {
// URL is the remote URL where the video can be fetched.
URL string
}
// NewVideoFunc creates a new VideoModel instance.
type NewVideoFunc func(...Option) VideoModel
var videoProviders = make(map[string]NewVideoFunc)
// RegisterVideo registers a video generation provider.
func RegisterVideo(name string, fn NewVideoFunc) {
videoProviders[name] = fn
}
// NewVideo creates a new VideoModel instance based on the provider name.
func NewVideo(provider string, opts ...Option) VideoModel {
if fn, ok := videoProviders[provider]; ok {
return fn(opts...)
}
return nil
}
+345
View File
@@ -0,0 +1,345 @@
# Auth Package Analysis
## Current Status: ✅ Fully Functional
The auth package is now **production-ready** with complete server/client wrappers and integration examples.
---
## ✅ What Exists
### 1. Core Interfaces (`auth.go`)
```go
type Auth interface {
Generate(id string, opts ...GenerateOption) (*Account, error)
Inspect(token string) (*Account, error)
Token(opts ...TokenOption) (*Token, error)
}
type Rules interface {
Verify(acc *Account, res *Resource, opts ...VerifyOption) error
Grant(rule *Rule) error
Revoke(rule *Rule) error
List(...ListOption) ([]*Rule, error)
}
```
**Status:** ✅ Well-designed, complete
### 2. Data Types
- `Account` - represents authenticated user/service
- `Token` - access/refresh token pair
- `Resource` - service endpoint to protect
- `Rule` - access control rule
- `Access` - grant/deny enum
**Status:** ✅ Complete
### 3. Implementations
**Noop Auth** (`noop.go`):
- For development/testing
- Always grants access
- No actual authentication
**Status:** ✅ Works for dev
**JWT Auth** (`jwt/jwt.go`):
- Uses RSA keys for signing
- Generates and verifies JWT tokens
- **⚠️ Problem:** Depends on external plugin `github.com/micro/plugins/v5/auth/jwt/token`
**Status:** ⚠️ External dependency
### 4. Authorization Logic (`rules.go`)
- Rule-based access control (RBAC)
- Supports wildcards (`*`)
- Priority-based rule evaluation
- Scope-based permissions
**Status:** ✅ Complete and tested
---
## ✅ Recently Completed
### 1. **Service Integration Wrapper** ✅
**Status:** IMPLEMENTED in `wrapper/auth/server.go`
```go
// AuthHandler wraps a service to enforce authentication
func AuthHandler(opts HandlerOptions) server.HandlerWrapper
func PublicEndpoints(...) HandlerOptions
func AuthRequired(...) HandlerOptions
func AuthOptional(authProvider auth.Auth) server.HandlerWrapper
```
Features:
- Token extraction from metadata
- Token verification with auth.Inspect()
- Authorization checks with rules.Verify()
- Account injection into context
- Skip endpoints support
- Comprehensive error handling (401/403)
### 2. **Client Wrapper** ✅
**Status:** IMPLEMENTED in `wrapper/auth/client.go`
```go
// AuthClient adds authentication tokens to client requests
func AuthClient(opts ClientOptions) client.Wrapper
func FromToken(token string) client.Wrapper
func FromContext(authProvider auth.Auth) client.Wrapper
```
Features:
- Automatic token injection
- Static token support
- Dynamic token generation from context
- Works with Call, Stream, and Publish
### 3. **Metadata Helpers** ✅
**Status:** IMPLEMENTED in `wrapper/auth/metadata.go`
```go
// Standard token extraction and injection
func TokenFromMetadata(md metadata.Metadata) (string, error)
func TokenToMetadata(md metadata.Metadata, token string) metadata.Metadata
func AccountFromMetadata(md metadata.Metadata, a auth.Auth) (*auth.Account, error)
```
Features:
- Bearer token extraction
- Case-insensitive header lookup
- Token format validation
- Direct account extraction
### 6. **Standalone JWT Implementation** ⚠️
**Status:** Partially complete (low priority)
Current JWT auth in `auth/jwt/jwt.go` depends on external plugin:
```go
jwtToken "github.com/micro/plugins/v5/auth/jwt/token"
```
**Note:** This is NOT a blocker. The wrappers work with any auth.Auth implementation including:
- JWT auth (with plugin dependency)
- Noop auth (for development)
- Custom auth implementations
**Future improvement:** Create self-contained JWT implementation to remove plugin dependency.
### 4. **Examples** ✅
**Status:** IMPLEMENTED in `examples/auth/`
Complete working example with:
- Protected Greeter service (server/)
- Client with authentication (client/)
- Proto definitions (proto/)
- Comprehensive README with:
- Architecture diagrams
- Code walkthrough
- Auth strategies
- Authorization rules
- Testing guide
- Production considerations
- Troubleshooting guide
### 5. **Documentation** ✅
**Status:** IMPLEMENTED
Complete documentation:
- `wrapper/auth/README.md` - Full API reference (200+ lines)
- `examples/auth/README.md` - Integration tutorial (400+ lines)
- Server wrapper documentation with examples
- Client wrapper documentation with examples
- Metadata helpers API reference
- Best practices guide
- Troubleshooting guide
- Production considerations
---
## 🔍 Detailed Analysis
### JWT Implementation Dependency Issue
File: `auth/jwt/jwt.go:7`
```go
jwtToken "github.com/micro/plugins/v5/auth/jwt/token"
```
This depends on:
- `github.com/micro/plugins` repository
- Must be separately installed
- May not be maintained
- Breaks self-contained promise
**Recommendation:** Create standalone JWT implementation in `auth/jwt/token/`
### Rules Verification Works Well
The `Verify()` function in `rules.go` is well-implemented:
- ✅ Handles wildcards correctly
- ✅ Priority-based evaluation
- ✅ Supports resource hierarchies (e.g., `/foo/*` matches `/foo/bar`)
- ✅ Public vs authenticated vs scoped access
- ✅ Tested (see `rules_test.go`)
### Context Integration Exists
```go
// From auth.go
func AccountFromContext(ctx context.Context) (*Account, bool)
func ContextWithAccount(ctx context.Context, account *Account) context.Context
```
This is ready to use once wrappers are implemented.
---
## 🛠️ Implementation Status
### Phase 1: Critical ✅ COMPLETE
1.**Server Wrapper** - `wrapper/auth/server.go`
- Token extraction from metadata
- Verification with auth.Inspect()
- Authorization with rules.Verify()
- Skip endpoints support
- Helper functions (AuthRequired, PublicEndpoints, AuthOptional)
2.**Client Wrapper** - `wrapper/auth/client.go`
- Adds Authorization header/metadata
- Static token support (FromToken)
- Dynamic token generation (FromContext)
- Works with Call, Stream, Publish
3.**Metadata Helpers** - `wrapper/auth/metadata.go`
- TokenFromMetadata - extract Bearer token
- TokenToMetadata - inject Bearer token
- AccountFromMetadata - extract and verify in one step
### Phase 2: Important ✅ COMPLETE
4. ⚠️ **Standalone JWT Implementation** - Deferred (not critical)
- Current JWT works with plugin
- Can use noop auth for development
- Future enhancement to remove plugin dependency
5. ⚠️ **Key Generation Utilities** - Deferred (not critical)
- JWT auth handles key management
- Future enhancement for convenience
6.**Examples** - `examples/auth/`
- Complete server/client example
- Protected and public endpoints
- Comprehensive README (400+ lines)
- Code walkthrough and best practices
### Phase 3: Production Ready ✅ COMPLETE
7. ⚠️ **Advanced Examples** - Future enhancement
- Basic example covers most use cases
- Can be added based on demand
8.**Documentation**
- `wrapper/auth/README.md` - Full API reference
- `examples/auth/README.md` - Integration guide
- Best practices and troubleshooting
9.**Testing Utilities**
- Noop auth for tests
- Token generation examples in docs
---
## 📋 Integration Checklist
To use auth with services, users need:
- [x] Auth interface and implementations
- [x] **Server wrapper to enforce auth**
- [x] **Client wrapper to send auth**
- [x] Metadata helpers ✅
- [x] Examples showing integration ✅
- [x] Documentation ✅
- [~] Working JWT implementation (has plugin dependency, not critical)
**Current completeness: ~95%** 🎉
The auth system is now fully functional and production-ready!
---
## 💡 Recommendations
### ✅ Completed
1.**Created wrapper/auth package** with server and client wrappers
2.**Wrote comprehensive examples** showing protected service
3.**Documented** integration patterns with 600+ lines of docs
### Optional Future Enhancements
4. **Remove plugin dependency** - create standalone JWT
- Current solution works fine with plugin
- Would reduce external dependencies
- Priority: Low
5. **Add to CLI** - `micro auth` commands for token management
- Generate tokens from CLI
- Inspect tokens
- Manage accounts
- Priority: Medium
6. **OAuth2 provider** - for enterprise SSO
- Integration with external identity providers
- Priority: Low (can use custom auth provider)
7. **API key auth** - simpler alternative to JWT
- For machine-to-machine auth
- Priority: Low
8. **Audit logging** - track auth events
- Who accessed what and when
- Priority: Medium
9. **Rate limiting** - per account/scope
- Prevent abuse
- Priority: Medium
---
## 🎉 Status: Auth System Complete
The auth system is now **fully functional and production-ready**!
**What's available:**
- ✅ Server wrapper for enforcing auth
- ✅ Client wrapper for adding auth
- ✅ Metadata helpers for token handling
- ✅ Complete working example
- ✅ Comprehensive documentation
- ✅ Best practices guide
- ✅ Troubleshooting guide
**Usage:**
```go
// Server
micro.WrapHandler(authWrapper.AuthHandler(...))
// Client
micro.WrapClient(authWrapper.FromToken(...))
```
See `examples/auth/` for complete working code!
+3 -3
View File
@@ -4,9 +4,9 @@ import (
"sync"
"time"
jwtToken "github.com/micro/plugins/v5/auth/jwt/token"
"go-micro.dev/v5/auth"
"go-micro.dev/v5/cmd"
"go-micro.dev/v6/auth"
jwtToken "go-micro.dev/v6/auth/jwt/token"
"go-micro.dev/v6/cmd"
)
func init() {
+5 -5
View File
@@ -4,8 +4,8 @@ import (
"encoding/base64"
"time"
"github.com/dgrijalva/jwt-go"
"go-micro.dev/v5/auth"
"github.com/golang-jwt/jwt/v5"
"go-micro.dev/v6/auth"
)
// authClaims to be encoded in the JWT.
@@ -14,7 +14,7 @@ type authClaims struct {
Scopes []string `json:"scopes"`
Metadata map[string]string `json:"metadata"`
jwt.StandardClaims
jwt.RegisteredClaims
}
// JWT implementation of token provider.
@@ -49,10 +49,10 @@ func (j *JWT) Generate(acc *auth.Account, opts ...GenerateOption) (*Token, error
// generate the JWT
expiry := time.Now().Add(options.Expiry)
t := jwt.NewWithClaims(jwt.SigningMethodRS256, authClaims{
acc.Type, acc.Scopes, acc.Metadata, jwt.StandardClaims{
acc.Type, acc.Scopes, acc.Metadata, jwt.RegisteredClaims{
Subject: acc.ID,
Issuer: acc.Issuer,
ExpiresAt: expiry.Unix(),
ExpiresAt: jwt.NewNumericDate(expiry),
},
})
tok, err := t.SignedString(key)
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"testing"
"time"
"go-micro.dev/v5/auth"
"go-micro.dev/v6/auth"
)
func TestGenerate(t *testing.T) {
+1 -1
View File
@@ -3,7 +3,7 @@ package token
import (
"time"
"go-micro.dev/v5/store"
"go-micro.dev/v6/store"
)
type Options struct {
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"errors"
"time"
"go-micro.dev/v5/auth"
"go-micro.dev/v6/auth"
)
var (
+45
View File
@@ -0,0 +1,45 @@
// Package noop provides a no-op auth implementation for testing and development.
//
// The noop auth provider:
// - Accepts any token (always returns a valid account)
// - Grants all permissions (no actual authorization)
// - Generates tokens (but doesn't verify them)
//
// This is useful for:
// - Local development
// - Testing
// - Prototyping
//
// DO NOT use in production. Use JWT auth or implement a custom auth provider instead.
package noop
import (
"go-micro.dev/v6/auth"
)
// NewAuth returns a new noop auth provider.
//
// The noop provider accepts all tokens and grants all permissions.
// This is for development and testing only - DO NOT use in production.
//
// Example:
//
// authProvider := noop.NewAuth()
// account, _ := authProvider.Generate("user123")
// token, _ := authProvider.Token(auth.WithCredentials(account.ID, account.Secret))
func NewAuth(opts ...auth.Option) auth.Auth {
return auth.NewAuth(opts...)
}
// NewRules returns a new noop rules implementation.
//
// The noop rules implementation grants all access and doesn't enforce any rules.
// This is for development and testing only.
//
// Example:
//
// rules := noop.NewRules()
// err := rules.Verify(account, resource) // Always returns nil
func NewRules() auth.Rules {
return auth.NewRules()
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"time"
"go-micro.dev/v5/logger"
"go-micro.dev/v6/logger"
)
func NewOptions(opts ...Option) Options {
+16 -16
View File
@@ -15,14 +15,14 @@ import (
"time"
"github.com/google/uuid"
"go-micro.dev/v5/codec/json"
merr "go-micro.dev/v5/errors"
"go-micro.dev/v5/registry"
"go-micro.dev/v5/registry/cache"
"go-micro.dev/v5/transport/headers"
maddr "go-micro.dev/v5/util/addr"
mnet "go-micro.dev/v5/util/net"
mls "go-micro.dev/v5/util/tls"
"go-micro.dev/v6/codec/json"
merr "go-micro.dev/v6/errors"
maddr "go-micro.dev/v6/internal/util/addr"
mnet "go-micro.dev/v6/internal/util/net"
mls "go-micro.dev/v6/internal/util/tls"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/registry/cache"
"go-micro.dev/v6/transport/headers"
"golang.org/x/net/http2"
)
@@ -100,7 +100,7 @@ func newTransport(config *tls.Config) *http.Transport {
})
// setup http2
http2.ConfigureTransport(t)
_ = http2.ConfigureTransport(t)
return t
}
@@ -288,19 +288,19 @@ func (h *httpBroker) run(l net.Listener) {
}
func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
if req.Method != http.MethodPost {
err := merr.BadRequest("go.micro.broker", "Method not allowed")
http.Error(w, err.Error(), http.StatusMethodNotAllowed)
return
}
defer req.Body.Close()
req.ParseForm()
_ = req.ParseForm()
b, err := io.ReadAll(req.Body)
if err != nil {
errr := merr.InternalServerError("go.micro.broker", "Error reading request body: %v", err)
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(errr.Error()))
return
}
@@ -308,7 +308,7 @@ func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var m *Message
if err = h.opts.Codec.Unmarshal(b, &m); err != nil {
errr := merr.InternalServerError("go.micro.broker", "Error parsing request body: %v", err)
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(errr.Error()))
return
}
@@ -318,7 +318,7 @@ func (h *httpBroker) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if len(topic) == 0 {
errr := merr.InternalServerError("go.micro.broker", "Topic not found")
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(errr.Error()))
return
}
@@ -406,7 +406,7 @@ func (h *httpBroker) Connect() error {
addr := h.address
h.address = l.Addr().String()
go http.Serve(l, h.mux)
go func() { _ = http.Serve(l, h.mux) }()
go func() {
h.run(l)
h.Lock()
@@ -555,7 +555,7 @@ func (h *httpBroker) Publish(topic string, msg *Message, opts ...PublishOption)
}
// discard response body
io.Copy(io.Discard, r.Body)
_, _ = io.Copy(io.Discard, r.Body)
r.Body.Close()
return nil
}
+5 -3
View File
@@ -6,8 +6,8 @@ import (
"time"
"github.com/google/uuid"
"go-micro.dev/v5/broker"
"go-micro.dev/v5/registry"
"go-micro.dev/v6/broker"
"go-micro.dev/v6/registry"
)
var (
@@ -161,7 +161,9 @@ func pub(b *testing.B, c int) {
go func() {
for range ch {
if err := brk.Publish(topic, msg); err != nil {
b.Fatalf("Unexpected publish error: %v", err)
b.Errorf("Unexpected publish error: %v", err)
wg.Done()
return
}
select {
case <-done:
+4 -5
View File
@@ -7,9 +7,9 @@ import (
"sync"
"github.com/google/uuid"
log "go-micro.dev/v5/logger"
maddr "go-micro.dev/v5/util/addr"
mnet "go-micro.dev/v5/util/net"
maddr "go-micro.dev/v6/internal/util/addr"
mnet "go-micro.dev/v6/internal/util/net"
log "go-micro.dev/v6/logger"
)
type memoryBroker struct {
@@ -122,7 +122,7 @@ func (m *memoryBroker) Publish(topic string, msg *Message, opts ...PublishOption
if err := sub.handler(p); err != nil {
p.err = err
if eh := m.opts.ErrorHandler; eh != nil {
eh(p)
_ = eh(p)
continue
}
return err
@@ -222,7 +222,6 @@ func (m *memorySubscriber) Unsubscribe() error {
func NewMemoryBroker(opts ...Option) Broker {
options := NewOptions(opts...)
return &memoryBroker{
opts: options,
Subscribers: make(map[string][]*memorySubscriber),
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"fmt"
"testing"
"go-micro.dev/v5/broker"
"go-micro.dev/v6/broker"
)
func TestMemoryBroker(t *testing.T) {
+1 -1
View File
@@ -3,7 +3,7 @@ package nats
import (
"context"
"go-micro.dev/v5/broker"
"go-micro.dev/v6/broker"
)
// setBrokerOption returns a function to setup a context with given value.
+134 -21
View File
@@ -6,12 +6,13 @@ import (
"errors"
"strings"
"sync"
"time"
natsp "github.com/nats-io/nats.go"
"go-micro.dev/v5/broker"
"go-micro.dev/v5/codec/json"
"go-micro.dev/v5/logger"
"go-micro.dev/v5/registry"
"go-micro.dev/v6/broker"
"go-micro.dev/v6/codec/json"
"go-micro.dev/v6/logger"
"go-micro.dev/v6/registry"
)
type natsBroker struct {
@@ -22,10 +23,15 @@ type natsBroker struct {
connected bool
addrs []string
conn *natsp.Conn
conn *natsp.Conn // single connection (used when pool is disabled)
pool *connectionPool // connection pool (used when pooling is enabled)
opts broker.Options
nopts natsp.Options
// pool configuration
poolSize int
poolIdleTimeout time.Duration
// should we drain the connection
drain bool
closeCh chan (error)
@@ -109,6 +115,39 @@ func (n *natsBroker) Connect() error {
return nil
}
// Check if we should use connection pooling
if n.poolSize > 1 {
// Initialize connection pool
factory := func() (*natsp.Conn, error) {
opts := n.nopts
opts.Servers = n.addrs
opts.Secure = n.opts.Secure
opts.TLSConfig = n.opts.TLSConfig
// secure might not be set
if n.opts.TLSConfig != nil {
opts.Secure = true
}
return opts.Connect()
}
pool, err := newConnectionPool(n.poolSize, factory)
if err != nil {
return err
}
// Set idle timeout if configured
if n.poolIdleTimeout > 0 {
pool.idleTimeout = n.poolIdleTimeout
}
n.pool = pool
n.connected = true
return nil
}
// Single connection mode (original behavior)
status := natsp.CLOSED
if n.conn != nil {
status = n.conn.Status()
@@ -143,14 +182,26 @@ func (n *natsBroker) Disconnect() error {
n.Lock()
defer n.Unlock()
// drain the connection if specified
if n.drain {
n.conn.Drain()
n.closeCh <- nil
// Close connection pool if it exists
if n.pool != nil {
if err := n.pool.Close(); err != nil {
n.opts.Logger.Log(logger.ErrorLevel, "error closing connection pool:", err)
}
n.pool = nil
}
// close the client connection
n.conn.Close()
// Close single connection if it exists
if n.conn != nil {
// drain the connection if specified
if n.drain {
_ = n.conn.Drain()
n.closeCh <- nil
}
// close the client connection
n.conn.Close()
n.conn = nil
}
// set not connected
n.connected = false
@@ -171,24 +222,42 @@ func (n *natsBroker) Publish(topic string, msg *broker.Message, opts ...broker.P
n.RLock()
defer n.RUnlock()
if n.conn == nil {
return errors.New("not connected")
}
b, err := n.opts.Codec.Marshal(msg)
if err != nil {
return err
}
// Use connection pool if enabled
if n.pool != nil {
poolConn, err := n.pool.Get()
if err != nil {
return err
}
defer func() { _ = n.pool.Put(poolConn) }()
conn := poolConn.Conn()
if conn == nil {
return errors.New("invalid connection from pool")
}
return conn.Publish(topic, b)
}
// Use single connection (original behavior)
if n.conn == nil {
return errors.New("not connected")
}
return n.conn.Publish(topic, b)
}
func (n *natsBroker) Subscribe(topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
n.RLock()
if n.conn == nil {
n.RUnlock()
hasConnection := n.conn != nil || n.pool != nil
n.RUnlock()
if !hasConnection {
return nil, errors.New("not connected")
}
n.RUnlock()
opt := broker.SubscribeOptions{
AutoAck: true,
@@ -210,7 +279,7 @@ func (n *natsBroker) Subscribe(topic string, handler broker.Handler, opts ...bro
m.Body = msg.Data
n.opts.Logger.Log(logger.ErrorLevel, err)
if eh != nil {
eh(pub)
_ = eh(pub)
}
return
}
@@ -218,7 +287,7 @@ func (n *natsBroker) Subscribe(topic string, handler broker.Handler, opts ...bro
pub.err = err
n.opts.Logger.Log(logger.ErrorLevel, err)
if eh != nil {
eh(pub)
_ = eh(pub)
}
}
}
@@ -226,6 +295,38 @@ func (n *natsBroker) Subscribe(topic string, handler broker.Handler, opts ...bro
var sub *natsp.Subscription
var err error
// Use connection pool if enabled
if n.pool != nil {
poolConn, err := n.pool.Get()
if err != nil {
return nil, err
}
conn := poolConn.Conn()
if conn == nil {
_ = n.pool.Put(poolConn)
return nil, errors.New("invalid connection from pool")
}
if len(opt.Queue) > 0 {
sub, err = conn.QueueSubscribe(topic, opt.Queue, fn)
} else {
sub, err = conn.Subscribe(topic, fn)
}
if err != nil {
_ = n.pool.Put(poolConn)
return nil, err
}
// Return connection to pool after subscription is created
// The subscription keeps the connection alive
_ = n.pool.Put(poolConn)
return &subscriber{s: sub, opts: opt}, nil
}
// Use single connection (original behavior)
n.RLock()
if len(opt.Queue) > 0 {
sub, err = n.conn.QueueSubscribe(topic, opt.Queue, fn)
@@ -248,14 +349,26 @@ func (n *natsBroker) setOption(opts ...broker.Option) {
o(&n.opts)
}
n.Once.Do(func() {
n.Do(func() {
n.nopts = natsp.GetDefaultOptions()
n.poolSize = 1 // Default to single connection (no pooling)
n.poolIdleTimeout = 5 * time.Minute
})
if nopts, ok := n.opts.Context.Value(optionsKey{}).(natsp.Options); ok {
n.nopts = nopts
}
// Set pool size if configured
if poolSize, ok := n.opts.Context.Value(poolSizeKey{}).(int); ok && poolSize > 0 {
n.poolSize = poolSize
}
// Set pool idle timeout if configured
if idleTimeout, ok := n.opts.Context.Value(poolIdleTimeoutKey{}).(time.Duration); ok {
n.poolIdleTimeout = idleTimeout
}
// broker.Options have higher priority than nats.Options
// only if Addrs, Secure or TLSConfig were not set through a broker.Option
// we read them from nats.Option
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"testing"
natsp "github.com/nats-io/nats.go"
"go-micro.dev/v5/broker"
"go-micro.dev/v6/broker"
)
var addrTestCases = []struct {
+19 -1
View File
@@ -1,12 +1,16 @@
package nats
import (
"time"
natsp "github.com/nats-io/nats.go"
"go-micro.dev/v5/broker"
"go-micro.dev/v6/broker"
)
type optionsKey struct{}
type drainConnectionKey struct{}
type poolSizeKey struct{}
type poolIdleTimeoutKey struct{}
// Options accepts nats.Options.
func Options(opts natsp.Options) broker.Option {
@@ -17,3 +21,17 @@ func Options(opts natsp.Options) broker.Option {
func DrainConnection() broker.Option {
return setBrokerOption(drainConnectionKey{}, struct{}{})
}
// PoolSize sets the size of the connection pool.
// If set to a value > 1, the broker will use a connection pool.
// Default is 1 (no pooling).
func PoolSize(size int) broker.Option {
return setBrokerOption(poolSizeKey{}, size)
}
// PoolIdleTimeout sets the timeout for idle connections in the pool.
// Connections idle for longer than this duration will be closed.
// Default is 5 minutes. Set to 0 to disable idle timeout.
func PoolIdleTimeout(timeout time.Duration) broker.Option {
return setBrokerOption(poolIdleTimeoutKey{}, timeout)
}
+188
View File
@@ -0,0 +1,188 @@
package nats
import (
"errors"
"sync"
"time"
natsp "github.com/nats-io/nats.go"
)
var (
// ErrPoolExhausted is returned when no connections are available in the pool
ErrPoolExhausted = errors.New("connection pool exhausted")
// ErrPoolClosed is returned when trying to use a closed pool
ErrPoolClosed = errors.New("connection pool is closed")
)
// connectionPool manages a pool of NATS connections
type connectionPool struct {
mu sync.RWMutex
connections chan *pooledConnection
factory func() (*natsp.Conn, error)
size int
idleTimeout time.Duration
closed bool
}
// pooledConnection wraps a NATS connection with metadata
type pooledConnection struct {
conn *natsp.Conn
createdAt time.Time
lastUsed time.Time
mu sync.Mutex
}
// newConnectionPool creates a new connection pool
func newConnectionPool(size int, factory func() (*natsp.Conn, error)) (*connectionPool, error) {
if size <= 0 {
size = 1
}
pool := &connectionPool{
connections: make(chan *pooledConnection, size),
factory: factory,
size: size,
idleTimeout: 5 * time.Minute,
closed: false,
}
return pool, nil
}
// Get retrieves a connection from the pool or creates a new one
func (p *connectionPool) Get() (*pooledConnection, error) {
p.mu.RLock()
if p.closed {
p.mu.RUnlock()
return nil, ErrPoolClosed
}
p.mu.RUnlock()
// Try to get an existing connection from the pool
select {
case conn := <-p.connections:
// Check if connection is still valid and not idle for too long
if conn.isValid() && !conn.isExpired(p.idleTimeout) {
conn.updateLastUsed()
return conn, nil
}
// Connection is invalid or expired, close it and create a new one
conn.close()
return p.createConnection()
default:
// No connection available, create a new one
return p.createConnection()
}
}
// Put returns a connection to the pool
func (p *connectionPool) Put(conn *pooledConnection) error {
p.mu.RLock()
defer p.mu.RUnlock()
if p.closed {
return conn.close()
}
// Check if connection is still valid
if !conn.isValid() {
return conn.close()
}
conn.updateLastUsed()
// Try to return connection to pool
select {
case p.connections <- conn:
return nil
default:
// Pool is full, close the connection
return conn.close()
}
}
// Close closes all connections in the pool
func (p *connectionPool) Close() error {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return nil
}
p.closed = true
close(p.connections)
// Close all connections in the pool
for conn := range p.connections {
conn.close()
}
return nil
}
// createConnection creates a new pooled connection
func (p *connectionPool) createConnection() (*pooledConnection, error) {
conn, err := p.factory()
if err != nil {
return nil, err
}
return &pooledConnection{
conn: conn,
createdAt: time.Now(),
lastUsed: time.Now(),
}, nil
}
// isValid checks if the underlying NATS connection is valid
func (pc *pooledConnection) isValid() bool {
pc.mu.Lock()
defer pc.mu.Unlock()
if pc.conn == nil {
return false
}
status := pc.conn.Status()
return status == natsp.CONNECTED || status == natsp.RECONNECTING
}
// isExpired checks if the connection has been idle for too long
func (pc *pooledConnection) isExpired(timeout time.Duration) bool {
pc.mu.Lock()
defer pc.mu.Unlock()
if timeout <= 0 {
return false
}
return time.Since(pc.lastUsed) > timeout
}
// close closes the underlying NATS connection
func (pc *pooledConnection) close() error {
pc.mu.Lock()
defer pc.mu.Unlock()
if pc.conn != nil {
pc.conn.Close()
pc.conn = nil
}
return nil
}
// Conn returns the underlying NATS connection
func (pc *pooledConnection) Conn() *natsp.Conn {
pc.mu.Lock()
defer pc.mu.Unlock()
return pc.conn
}
// updateLastUsed updates the last used timestamp in a thread-safe manner
func (pc *pooledConnection) updateLastUsed() {
pc.mu.Lock()
defer pc.mu.Unlock()
pc.lastUsed = time.Now()
}
+204
View File
@@ -0,0 +1,204 @@
package nats
import (
"sync"
"testing"
"time"
natsp "github.com/nats-io/nats.go"
)
func TestConnectionPool_GetPut(t *testing.T) {
// Mock factory that creates connections
connCount := 0
factory := func() (*natsp.Conn, error) {
connCount++
// Return a mock connection (we can't create real NATS connections in tests without a server)
// This test is more about the pool logic
return nil, nil
}
pool, err := newConnectionPool(3, factory)
if err != nil {
t.Fatalf("Failed to create pool: %v", err)
}
defer pool.Close()
// Get a connection (should create one)
conn1, err := pool.Get()
if err != nil {
t.Fatalf("Failed to get connection: %v", err)
}
if conn1 == nil {
t.Fatal("Expected connection, got nil")
}
// Put it back
if err := pool.Put(conn1); err != nil {
t.Fatalf("Failed to put connection: %v", err)
}
// Get it again (should reuse the same one)
conn2, err := pool.Get()
if err != nil {
t.Fatalf("Failed to get connection: %v", err)
}
// Since we can't compare actual connections easily, just verify we got one
if conn2 == nil {
t.Fatal("Expected connection, got nil")
}
}
func TestConnectionPool_Concurrent(t *testing.T) {
connCount := 0
mu := sync.Mutex{}
factory := func() (*natsp.Conn, error) {
mu.Lock()
connCount++
mu.Unlock()
return nil, nil
}
pool, err := newConnectionPool(5, factory)
if err != nil {
t.Fatalf("Failed to create pool: %v", err)
}
defer pool.Close()
// Simulate concurrent access
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
conn, err := pool.Get()
if err != nil {
t.Errorf("Failed to get connection: %v", err)
return
}
// Simulate some work
time.Sleep(10 * time.Millisecond)
if err := pool.Put(conn); err != nil {
t.Errorf("Failed to put connection: %v", err)
}
}()
}
wg.Wait()
// We should have created some connections
mu.Lock()
if connCount == 0 {
t.Error("Expected at least one connection to be created")
}
mu.Unlock()
}
func TestConnectionPool_Close(t *testing.T) {
factory := func() (*natsp.Conn, error) {
return nil, nil
}
pool, err := newConnectionPool(3, factory)
if err != nil {
t.Fatalf("Failed to create pool: %v", err)
}
// Get a connection
conn, err := pool.Get()
if err != nil {
t.Fatalf("Failed to get connection: %v", err)
}
// Close the pool
if err := pool.Close(); err != nil {
t.Fatalf("Failed to close pool: %v", err)
}
// Put connection back to closed pool should not panic
// The connection will be closed instead of returned to pool
_ = pool.Put(conn)
// Try to get from closed pool
_, err = pool.Get()
if err != ErrPoolClosed {
t.Errorf("Expected ErrPoolClosed, got: %v", err)
}
}
func TestPooledConnection_IsValid(t *testing.T) {
pc := &pooledConnection{
conn: nil, // nil connection should be invalid
createdAt: time.Now(),
lastUsed: time.Now(),
}
if pc.isValid() {
t.Error("Expected nil connection to be invalid")
}
}
func TestPooledConnection_IsExpired(t *testing.T) {
pc := &pooledConnection{
conn: nil,
createdAt: time.Now(),
lastUsed: time.Now().Add(-10 * time.Minute), // 10 minutes ago
}
// With 5 minute timeout, should be expired
if !pc.isExpired(5 * time.Minute) {
t.Error("Expected connection to be expired")
}
// With 0 timeout, should never expire
if pc.isExpired(0) {
t.Error("Expected connection not to expire with 0 timeout")
}
// With 20 minute timeout, should not be expired
if pc.isExpired(20 * time.Minute) {
t.Error("Expected connection not to be expired")
}
}
func TestNatsBroker_PoolConfiguration(t *testing.T) {
// Test that pool size is set correctly
br := NewNatsBroker(PoolSize(5))
nb, ok := br.(*natsBroker)
if !ok {
t.Fatal("Expected broker to be of type *natsBroker")
}
if nb.poolSize != 5 {
t.Errorf("Expected pool size 5, got %d", nb.poolSize)
}
// Test with custom idle timeout
br2 := NewNatsBroker(PoolSize(3), PoolIdleTimeout(10*time.Minute))
nb2, ok := br2.(*natsBroker)
if !ok {
t.Fatal("Expected broker to be of type *natsBroker")
}
if nb2.poolSize != 3 {
t.Errorf("Expected pool size 3, got %d", nb2.poolSize)
}
if nb2.poolIdleTimeout != 10*time.Minute {
t.Errorf("Expected idle timeout 10m, got %v", nb2.poolIdleTimeout)
}
}
func TestNatsBroker_DefaultSingleConnection(t *testing.T) {
// Test that default behavior is single connection (pool size 1)
br := NewNatsBroker()
nb, ok := br.(*natsBroker)
if !ok {
t.Fatal("Expected broker to be of type *natsBroker")
}
if nb.poolSize != 1 {
t.Errorf("Expected default pool size 1, got %d", nb.poolSize)
}
}
+3 -3
View File
@@ -4,9 +4,9 @@ import (
"context"
"crypto/tls"
"go-micro.dev/v5/codec"
"go-micro.dev/v5/logger"
"go-micro.dev/v5/registry"
"go-micro.dev/v6/codec"
"go-micro.dev/v6/logger"
"go-micro.dev/v6/registry"
)
type Options struct {
+4 -4
View File
@@ -61,14 +61,14 @@ func (r *rabbitMQChannel) Connect(prefetchCount int, prefetchGlobal bool, confir
func (r *rabbitMQChannel) Close() error {
if r.channel == nil {
return errors.New("Channel is nil")
return errors.New("channel is nil")
}
return r.channel.Close()
}
func (r *rabbitMQChannel) Publish(exchange, key string, message amqp.Publishing) error {
if r.channel == nil {
return errors.New("Channel is nil")
return errors.New("channel is nil")
}
if r.confirmPublish != nil {
@@ -84,11 +84,11 @@ func (r *rabbitMQChannel) Publish(exchange, key string, message amqp.Publishing)
if r.confirmPublish != nil {
confirmation, ok := <-r.confirmPublish
if !ok {
return errors.New("Channel closed before could receive confirmation of publish")
return errors.New("channel closed before could receive confirmation of publish")
}
if !confirmation.Ack {
return errors.New("Could not publish message, received nack from broker on confirmation")
return errors.New("could not publish message, received nack from broker on confirmation")
}
}
+6 -8
View File
@@ -11,16 +11,16 @@ import (
"time"
amqp "github.com/rabbitmq/amqp091-go"
"go-micro.dev/v5/logger"
mtls "go-micro.dev/v5/util/tls"
mtls "go-micro.dev/v6/internal/util/tls"
"go-micro.dev/v6/logger"
)
type MQExchangeType string
const (
ExchangeTypeFanout MQExchangeType = "fanout"
ExchangeTypeTopic = "topic"
ExchangeTypeDirect = "direct"
ExchangeTypeTopic MQExchangeType = "topic"
ExchangeTypeDirect MQExchangeType = "direct"
)
var (
@@ -46,8 +46,6 @@ var (
Locale: defaultLocale,
}
dial = amqp.Dial
dialTLS = amqp.DialTLS
dialConfig = amqp.DialConfig
)
@@ -251,9 +249,9 @@ func (r *rabbitMQConn) tryConnect(secure bool, config *amqp.Config) error {
if !r.withoutExchange {
if r.exchange.Durable {
r.Channel.DeclareDurableExchange(r.exchange)
_ = r.Channel.DeclareDurableExchange(r.exchange)
} else {
r.Channel.DeclareExchange(r.exchange)
_ = r.Channel.DeclareExchange(r.exchange)
}
r.ExchangeChannel, err = newRabbitChannel(r.Connection, r.prefetchCount, r.prefetchGlobal, r.confirmPublish)
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"testing"
amqp "github.com/rabbitmq/amqp091-go"
"go-micro.dev/v5/logger"
"go-micro.dev/v6/logger"
)
func TestNewRabbitMQConnURL(t *testing.T) {
+2 -2
View File
@@ -3,8 +3,8 @@ package rabbitmq
import (
"context"
"go-micro.dev/v5/broker"
"go-micro.dev/v5/server"
"go-micro.dev/v6/broker"
"go-micro.dev/v6/server"
)
// setSubscribeOption returns a function to setup a context with given value.
+3 -3
View File
@@ -4,9 +4,9 @@ import (
"context"
"time"
"go-micro.dev/v5/broker"
"go-micro.dev/v5/client"
"go-micro.dev/v5/server"
"go-micro.dev/v6/broker"
"go-micro.dev/v6/client"
"go-micro.dev/v6/server"
)
type durableQueueKey struct{}
+9 -11
View File
@@ -10,18 +10,16 @@ import (
"time"
amqp "github.com/rabbitmq/amqp091-go"
"go-micro.dev/v5/broker"
"go-micro.dev/v5/logger"
"go-micro.dev/v6/broker"
"go-micro.dev/v6/logger"
)
type rbroker struct {
conn *rabbitMQConn
addrs []string
opts broker.Options
prefetchCount int
prefetchGlobal bool
mtx sync.Mutex
wg sync.WaitGroup
conn *rabbitMQConn
addrs []string
opts broker.Options
mtx sync.Mutex
wg sync.WaitGroup
}
type subscriber struct {
@@ -304,9 +302,9 @@ func (r *rbroker) Subscribe(topic string, handler broker.Handler, opts ...broker
p := &publication{d: msg, m: m, t: msg.RoutingKey}
p.err = handler(p)
if p.err == nil && ackSuccess && !opt.AutoAck {
msg.Ack(false)
_ = msg.Ack(false)
} else if p.err != nil && !opt.AutoAck {
msg.Nack(false, requeueOnError)
_ = msg.Nack(false, requeueOnError)
}
}
+14 -19
View File
@@ -7,12 +7,12 @@ import (
"testing"
"time"
"go-micro.dev/v5/logger"
"go-micro.dev/v6/logger"
micro "go-micro.dev/v5"
broker "go-micro.dev/v5/broker"
rabbitmq "go-micro.dev/v5/broker/rabbitmq"
server "go-micro.dev/v5/server"
micro "go-micro.dev/v6"
broker "go-micro.dev/v6/broker"
rabbitmq "go-micro.dev/v6/broker/rabbitmq"
server "go-micro.dev/v6/server"
)
type Example struct{}
@@ -50,8 +50,7 @@ func TestDurable(t *testing.T) {
s := server.NewServer(server.Broker(b))
service := micro.NewService(
micro.Server(s),
service := micro.NewService("test", micro.Server(s),
micro.Broker(b),
)
h := &Example{}
@@ -82,8 +81,7 @@ func TestWithoutExchange(t *testing.T) {
s := server.NewServer(server.Broker(b))
service := micro.NewService(
micro.Server(s),
service := micro.NewService("test", micro.Server(s),
micro.Broker(b),
)
brkrSub := broker.NewSubscribeOptions(
@@ -119,7 +117,7 @@ func TestWithoutExchange(t *testing.T) {
rabbitmq.DeliveryMode(2),
rabbitmq.ContentType("application/json"))
if err != nil {
t.Fatal(err)
t.Errorf("%v", err)
}
}()
@@ -140,8 +138,7 @@ func TestFanoutExchange(t *testing.T) {
s := server.NewServer(server.Broker(b))
service := micro.NewService(
micro.Server(s),
service := micro.NewService("test", micro.Server(s),
micro.Broker(b),
)
brkrSub := broker.NewSubscribeOptions(
@@ -177,7 +174,7 @@ func TestFanoutExchange(t *testing.T) {
rabbitmq.DeliveryMode(2),
rabbitmq.ContentType("application/json"))
if err != nil {
t.Fatal(err)
t.Errorf("%v", err)
}
}()
@@ -198,8 +195,7 @@ func TestDirectExchange(t *testing.T) {
s := server.NewServer(server.Broker(b))
service := micro.NewService(
micro.Server(s),
service := micro.NewService("test", micro.Server(s),
micro.Broker(b),
)
brkrSub := broker.NewSubscribeOptions(
@@ -235,7 +231,7 @@ func TestDirectExchange(t *testing.T) {
rabbitmq.DeliveryMode(2),
rabbitmq.ContentType("application/json"))
if err != nil {
t.Fatal(err)
t.Errorf("%v", err)
}
}()
@@ -256,8 +252,7 @@ func TestTopicExchange(t *testing.T) {
s := server.NewServer(server.Broker(b))
service := micro.NewService(
micro.Server(s),
service := micro.NewService("test", micro.Server(s),
micro.Broker(b),
)
brkrSub := broker.NewSubscribeOptions(
@@ -293,7 +288,7 @@ func TestTopicExchange(t *testing.T) {
rabbitmq.DeliveryMode(2),
rabbitmq.ContentType("application/json"))
if err != nil {
t.Fatal(err)
t.Errorf("%v", err)
}
}()
+7 -7
View File
@@ -14,8 +14,8 @@ type memCache struct {
}
func (c *memCache) Get(ctx context.Context, key string) (interface{}, time.Time, error) {
c.RWMutex.RLock()
defer c.RWMutex.RUnlock()
c.RLock()
defer c.RUnlock()
item, found := c.items[key]
if !found {
@@ -37,8 +37,8 @@ func (c *memCache) Put(ctx context.Context, key string, val interface{}, d time.
e = time.Now().Add(d).UnixNano()
}
c.RWMutex.Lock()
defer c.RWMutex.Unlock()
c.Lock()
defer c.Unlock()
c.items[key] = Item{
Value: val,
@@ -49,8 +49,8 @@ func (c *memCache) Put(ctx context.Context, key string, val interface{}, d time.
}
func (c *memCache) Delete(ctx context.Context, key string) error {
c.RWMutex.Lock()
defer c.RWMutex.Unlock()
c.Lock()
defer c.Unlock()
_, found := c.items[key]
if !found {
@@ -61,6 +61,6 @@ func (c *memCache) Delete(ctx context.Context, key string) error {
return nil
}
func (m *memCache) String() string {
func (c *memCache) String() string {
return "memory"
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"time"
"go-micro.dev/v5/logger"
"go-micro.dev/v6/logger"
)
// Options represents the options for the cache.
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
rclient "github.com/go-redis/redis/v8"
"go-micro.dev/v5/cache"
"go-micro.dev/v6/cache"
)
type redisOptionsContextKey struct{}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"testing"
rclient "github.com/go-redis/redis/v8"
"go-micro.dev/v5/cache"
"go-micro.dev/v6/cache"
)
func Test_newUniversalClient(t *testing.T) {

Some files were not shown because too many files have changed in this diff Show More