Compare commits

...

76 Commits

Author SHA1 Message Date
Asim Aslam 95280adfb5 feat(cache): upgrade Redis client to v9 (#4891)
Co-authored-by: Codex <codex@openai.com>
2026-08-19 15:41:04 +01:00
Asim Aslam b263fe4394 Update GitHub funding information (#4888) 2026-08-16 10:16:49 +01:00
Asim Aslam f521f3474a revert: preserve full phantom tag prefixes (#4887)
* fix(retract): preserve non-major module tag prefixes

* Revert "fix(retract): preserve non-major module tag prefixes"

This reverts commit 4485463376.

---------

Co-authored-by: Codex <codex@openai.com>
2026-08-12 10:29:13 +01:00
Asim Aslam 7a8a13aa77 fix(retract): preserve non-major module tag prefixes (#4886)
Co-authored-by: Codex <codex@openai.com>
2026-08-12 10:27:59 +01:00
Alexander Serheyev edbe3663a0 chore(retract): miss paths, second round (#4884)
* chore(retract): miss paths, second round

* chore(retract): root retraction tags for tilde phantom paths

* fix(retract): skip blank lines during path dedup

Empty base buckets emit one blank line from printf; mapfile then reads it
as an empty element, inflating the total and creating bogus one-path
orphan commits. Filter blank lines before dedup.
2026-08-12 07:22:00 +01:00
Asim Aslam 0c64f18815 fix(retract): reliably push generated tag batches (#4885)
* chore(retract): miss paths, second round

* chore(retract): root retraction tags for tilde phantom paths

* fix(retract): skip blank lines during path dedup

Empty base buckets emit one blank line from printf; mapfile then reads it
as an empty element, inflating the total and creating bogus one-path
orphan commits. Filter blank lines before dedup.

* fix(retract): push tag batches without array slicing

---------

Co-authored-by: Alex Serheyev <74361701+alex-dna-tech@users.noreply.github.com>
Co-authored-by: Codex <codex@openai.com>
2026-08-11 17:40:37 +01:00
Alexander Serheyev 1c4bdab123 arch: decouple HTTP API gateway and MCP gateway via shared service resolver, add HTTP SSE support (#4882)
* arch: decouple HTTP API gateway and MCP gateway via shared schema resolver

- Add gateway/schema: shared registry watcher and endpoint schema parser
  used by both gateways, replacing duplicated discovery logic in gateway/mcp
- gateway/mcp: consume schema.Resolver; add NewServer for independent
  lifecycle (discovery/watching in NewServer, transport in Serve, shutdown
  via Stop)
- gateway/api: remove MCPEnabled/MCPAddress fields and background MCP
  spawning; the HTTP gateway no longer starts MCP
- cmd/micro/run and cmd/micro/gateway: instantiate and orchestrate both
  gateways explicitly, shutting down together on signal or first exit
- Mark gateway decoupling tickets 01-03 done

* feat(mcp): add streamable-HTTP transport for browser MCP clients

Implement the MCP streamable-HTTP spec at /mcp: POST JSON-RPC (batches,
notifications -> 202), GET SSE stream with heartbeat and session
lifecycle, DELETE session teardown, Mcp-Session-Id minted on initialize,
30-min idle session sweep. Tool dispatch shares invokeTool with the
legacy /mcp/call route; x402 challenge and tool-execution errors surface
as isError results.

Fixes browser-based clients (llama.cpp web UI): CORS preflight allows
mcp-protocol-version, and serveHTTP now shuts down the HTTP server when
the context is canceled so Ctrl-C/SIGTERM terminate cleanly.

* docs(website): document streamable-HTTP MCP transport and gateway decoupling
2026-08-11 16:50:20 +01:00
Alexander Serheyev 77fc793d5b feat(grpc): reflection option and native gRPC example (#4881)
* feat(grpc): reflection option and native gRPC example

Add grpcserver.Reflection() to register go-micro handlers with gRPC's
reflection service, and examples/grpc showing a go-micro v6 service
callable by grpcurl and any standard gRPC client.

Resolves micro/go-micro#4880

* docs(grpc): native gRPC compatibility guide with reflection

Update grpc-compatibility guide for the reflection option and
server.Name placement on the gRPC server; remove duplicated intro
text on ai-integration and add client-server description.
2026-08-07 10:13:29 +01:00
Alexander Serheyev a6d4272e21 cmd/micro gateway HTTP->RPC proxy: Endpoint handling via URL parsing is not implemented (#4879)
* fix(gateway): add /api/{service}/{method} HTTP-to-RPC proxy

The gateway only rendered the /api explorer page; any /api/{service}/{endpoint}
path fell through to 404. Add a proxy that resolves the endpoint from the
registry, checks scopes, and forwards the request body to the RPC client.
Accepts both /api/{service}/{method} and /api/{service}/{pkg}/{method} forms.

* fix(readme): old links, add protoc and docs for docker

* test(store): de-flake file store expiry window in first block

The initial record used a 150ms expiry read back immediately after a
bbolt write. Under -race/-cover on a loaded runner, the fsync'd write
or instrumented read can exceed 150ms, so the record has already
expired and Read("Hello") returns ErrNotFound, failing the test early.

Widen the first block to the same 1s expiry / 2s sleep pattern used by
the sibling blocks since #3789/#3828. The pre-expiry read stays well
inside 1s; the post-expiry read comfortably exceeds it.
2026-08-06 07:27:59 +01:00
Matt Van Horn b0d4ac7e01 fix: preserve AtlasCloud conformance markers across text tool fallbacks (#4878)
Fixes #4729

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-08-04 10:43:16 +01:00
Alexander Serheyev 7159377515 fix(website): uglyURLs on main, update documentation (#4871)
* fix(website): more uglyURLs on main page

* docs(website): fix contributing doc paths and jekyll references

* docs(website): dedupe duplicate pages, standardize on _index.md sections

Remove duplicate page titles in internal/website/content/en so every
title resolves to a single canonical page. Precedence: directory index
pages with bundled images, then the most complete content; draft copies
were dropped.

Removed duplicates (kept page in parentheses):
- docs/overview/*/index.md (dir index + image) vs docs/*.md for
  ai-integration, architecture, config, getting-started, observability
- docs/interfaces/{broker,registry,transport}/index.md (dir index +
  image) vs docs/{broker,registry,transport}.md
- docs/interfaces/{plugins,store}.md vs docs/{plugins,store}.md
- docs/contributing.md and docs/guides/contributing.md vs
  docs/project/contributing.md
- docs/guides/quickstart.md vs docs/quickstart.md
- docs/overview/performance.md vs docs/performance.md
- docs/project/{roadmap,roadmap-2026}.md vs docs/roadmap.md
- docs/architecture/{index,adr-*}.md (already mirrored and kept in
  docs/project/architecture/, whose index now links the available ADRs)
- docs/model.md vs docs/model/index.md
- blog/news/agent-guardrails.md vs docs/guides/agent-guardrails.md
- docs/examples/learn-by-examples/* (near-identical copies) vs
  docs/examples/*
- docs/overview/{REFLECTION-EVALUATION-SUMMARY,TLS_SECURITY_UPDATE}.md
  (draft copies)
- docs/index.md and docs/examples/index.md symlinks vs their _index.md

Frontmatter tidy: add missing descriptions (store, atlas-cloud, model),
drop weight/draft overrides, consolidate the Architecture Decision
Records index, and remove dead CSS overrides from _styles_project.scss.

Hugo conventions: _index.md is the branch/section bundle for a
directory - it is the landing page for a doc section that lists its
children. index.md is a leaf bundle - a standalone page at the exact
directory URL whose directory bundles its own resources (images, etc.).
The docs site standardizes on _index.md for section landing pages, so
the redundant index.md symlinks were removed and the duplicate
Architecture directory was merged into the project/architecture section.

* refactor(website): merge duplicates

* docs(website): fix relative links and wayfinding tests after Hugo migration

Replace Jekyll-era .html links with .md/index.md targets, fix relative
paths for pages moved into Hugo bundles, restore the ADR files dropped by
the duplicate-merge refactor, and update zero-to-hero-ci docs tests to the
content/en/docs layout.

* test(cmd/micro): expect .md guide links in docs, translate for CLI alignment

* docs(website): drop duplicate h1s, promote titles, backfill descriptions
2026-08-04 10:01:04 +01:00
Asim Aslam 3c39d17fad feat(gateway): auth follows the socket, not the subcommand (#4877)
Auth is a policy of exposure, not of which command you typed. The bind
address decides the default and there is never a default credential.

- Address-based default: loopback (127.0.0.1/localhost/::1) => auth off;
  non-loopback (0.0.0.0/routable) => auth on. micro run now binds
  127.0.0.1:8080 by default, so the dev loop and localhost MCP clients
  work with no login; micro gateway keeps :8080 (exposed => on).
- No default credential: stop creating admin/micro. When auth is on, use
  --auth-token / MICRO_AUTH_TOKEN or generate a machine token and print it
  once. It is accepted as an admin (constant-time compare) alongside JWTs.
- Token for machines, login for the browser: /api and /mcp accept
  Authorization: Bearer and a ?token= query param (for SSE / links).
- Explicit override both ways: --auth/--no-auth and MICRO_AUTH=on|off,
  shared by run and gateway via AuthFlags.
- Capability-aware even locally: checkEndpointScopes no longer short-
  circuits when auth is off, so a tool with a required scope (actions,
  paid) still needs a token+scope on a loopback gateway; read-only tools
  stay open.

Adds gateway/auth.go (isExposed, ResolveAuth, static token, AuthFlags)
with tests, updates the run banner and the micro-run guide. Smoke-tested:
loopback /api open (404 no-service, not 401); exposed /api 401 without a
token and authenticated with Bearer or ?token=; no admin/micro created.

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-02 12:24:28 +01:00
Asim Aslam a85509bc6f refactor(cli): consolidate the gateway into micro gateway (#4876)
Rename `micro server` to `micro gateway` and fold the standalone
micro-mcp-gateway binary into it, so there is one gateway with one name.

- Rename command server -> gateway (package cmd/micro/server ->
  cmd/micro/gateway; update the run and main importers).
- `micro gateway` gains the MCP production controls the standalone binary
  had: --rate-limit/--rate-burst, --auth, --audit, --scope,
  --circuit-breaker[-timeout], and --x402-*. When --mcp-address is set it
  runs the full gateway/mcp with those options; registry selection uses
  the CLI global --registry/--registry_address flags.
- `micro server` stays as a hidden, deprecated alias that warns and
  delegates, so existing invocations keep working.
- Delete cmd/micro-mcp-gateway (binary + Dockerfile). goreleaser only
  builds ./cmd/micro, so releases are unaffected.
- Repoint deploy/refs at the micro CLI image: Dockerfile CMD -> gateway;
  Helm chart runs `micro gateway --mcp-address` with registry via
  MICRO_REGISTRY env, image ghcr.io/micro/go-micro; drop the v6
  micro-mcp-gateway vanity entry and rename server -> gateway; update the
  docs guides and CLAUDE.md.

Build, vet, gofmt, and the run/gateway/cmd tests pass; `micro gateway`
and the hidden `micro server` alias both resolve.

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-02 12:01:42 +01:00
Asim Aslam 80aafc3b29 fix(run): scope micro run as a dev tool and harden the dev loop (#4875)
micro run is the local development inner loop, not a production runtime.
Make that explicit and fix real dev-UX bugs:

- Clean shutdown: the new-service scanner shared the signal channel with
  the main wait; a signal goes to one receiver, so it could steal Ctrl-C
  and hang teardown. Give background goroutines a dedicated shutdown
  channel and guard the services slice with a mutex (also fixes a data
  race on that slice during shutdown).
- Hot reload no longer takes a service offline on a compile error: build
  into a temp binary first and only swap+restart if the build succeeds;
  on failure the previous version keeps serving and the error is printed.
- Raise the log scanner buffer so long lines (JSON logs, stack traces)
  no longer overflow it and silently drop a services logs.
- Help text and the micro run guide now state plainly it is a dev tool
  with no daemon, and point to systemd/Docker/Kubernetes for production.
  Remove the guides fictional micro logs/status/stop commands (no such
  commands exist) and describe the real lifecycle (Ctrl-C, log files).

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-02 12:01:28 +01:00
Asim Aslam 4ab40dce6d fix(retract): avoid races with remotely published tags (#4874)
* fix(retract): dedupe phantom paths and tag refs before push

Duplicate PHANTOM_PATHS entries and cross-base path collisions produced the
same refs/tags/<rel>/v1.18.2 multiple times in a single git push, failing
with 'dst ref receives from more than one src'. Dedupe each per-base array
and sort -u CREATED_TAGS before pushing.

* perf(retract): batch orphan commit and tag creation with git fast-import

The previous flow spawned git subprocesses for every phantom path
(hash-object, update-index, rev-parse, tag -a ~40k processes for ~11k
paths), taking ~80 min. Now a single git fast-import per base writes all
go.mod blobs, the orphan commit, and its annotated tags in one process,
existing tags are snapshotted once with for-each-ref, and refname checks
use a bash fast path with git check-ref-format as fallback. Full run now
completes in ~5s with identical output.

* fix(retract): skip tags already published remotely

---------

Co-authored-by: Alex Serheyev <74361701+alex-dna-tech@users.noreply.github.com>
Co-authored-by: Codex <codex@openai.com>
2026-08-01 10:09:01 +01:00
Alexander Serheyev 71e17fd2da test: update harness workflow contract for owner-only schedule (#4872) 2026-07-31 07:59:35 +01:00
Alexander Serheyev a7fffdeb19 fix(ci): restrict hourly schedule to owner repo micro/go-micro (#4870)
The hourly cron was triggering on all forks, burning CI minutes and
potentially consuming API keys on fork variants with configured secrets.
Add github.repository checks so both harness jobs only run on schedule
when the owner is micro/go-micro. Manual workflow_dispatch is unaffected.
2026-07-30 19:40:54 +01:00
Asim Aslam 8167be77a4 docs(website): drop references to nonexistent micro/blog repo (#4869)
The "your microservices are already an AI platform" post and the
micro-run guide pointed at github.com/micro/blog as a real example repo,
but it does not exist — the links 404 and `micro run github.com/micro/blog`
would fail. Reword to describe the illustrative blogging platform without
claiming a backing repo, point the runnable example at the in-repo
examples/mcp/platform, and use placeholder names in the compose/run
snippets.

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-30 15:35:24 +01:00
Alexander Serheyev c3b5315758 Add retract-phantom.sh for proxy cache retraction of phantom module paths (#4856)
* Add retract-phantom.sh for proxy cache retraction of phantom module paths

Orphan-commit based retraction script for phantom module paths that
the Go proxy has cached but don't exist on master. Creates empty orphan
commits with retraction go.mod files, tags them per phantom path, then
pushes to origin. Master is never touched.

Phantom paths covered:
- v6: api
- v5: api/api, api/gateway, api/genproto, api/handler, api/handler/http
- v4: a, a/codec/proto, a/transport/memory

Usage:
  ./retract-phantom.sh --dry-run   # preview tags
  ./retract-phantom.sh             # create local tags
  ./retract-phantom.sh --push      # push tags to origin

After push, verify:
  go list -m -versions go-micro.dev/v5/api/handler  # → no versions
  go install go-micro.dev/v5/api/handler@latest     # → falls back to root

* Fix sanity check: check for go.mod, not directory existence

Directories like gateway/ and Debug/ exist on master but have no go.mod
file — they are not Go modules. The proxy caches them as separate
modules, so they are phantoms that need retraction.

Changed: [[ -d "$rel" ]] → [[ -f "$rel/go.mod" ]]

* Use 3 shared orphan commits instead of 10K individual ones

Each module base (v4, v5, v6) now gets a single orphan commit containing
all go.mod files for its phantom paths, rather than one orphan commit per
path. This reduces orphan commits from 10,207 to 3 while keeping the same
10,207 tags.

Dry-run now skips orphan creation entirely (prints summary instead).

* fix: retract phantom paths without nuking the tree; add pilot + scoped push

The script previously ran `git rm -rf .` + `git clean -fdx` in the repo,
which wiped the working tree (and the script itself), and built commits
with a broken `${BASES_${label}[@]}` expansion and a lowercase/`vN` label
mismatch that produced empty commits and no tags. Rewrote the commit step
to use git plumbing (hash-object/update-index/write-tree/commit-tree) so it
touches neither the working tree nor any branch, and fixed the path array
deref.

Also:
- add --pilot (first path per base) and a real --push that pushes only the
  new phantom tags (chunked, never `git push --tags`);
- make tagging idempotent (skip existing tags) and skip paths whose tag name
  is invalid per git check-ref-format (e.g. the `protoc-gen-micro~` entry,
  now removed from the list);
- move the retract rationale comment directly above the directive per docs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* retract: add v0 (no-version-suffix) phantom paths to retraction

Closes #4856

Adds 590 non-versioned phantom module paths (go-micro.dev/... without
v-suffix) to the retract-phantom.sh script. These modules were cached
by the Go proxy as separate module paths despite living in the same
repo tree, causing the same resolution issues as v6/v5/v4.

Evidence: go list -m -versions go-micro.dev/V4.9.0
go-micro.dev/V4.9.0 v0.1.0 v0.1.1 v0.1.2 v0.1.3 v0.1.4 v0.2.0 v0.3.0
v0.4.0 v0.5.0 v0.6.0 v0.7.0 v0.8.0 v0.9.0 v0.10.0 v0.11.0 v0.12.0
v0.13.0 v0.14.0 v0.14.1 v0.15.0 v0.15.1 v0.16.0 v0.17.0 v0.20.0
v0.21.0 v0.22.0 v0.22.1 v0.23.0 v0.24.0 v0.24.1 v0.25.0 v0.26.0
v0.26.1 v0.27.0 v0.27.1 v1.0.0 v1.1.0 v1.2.0 v1.3.0 v1.3.1 v1.4.0
v1.5.0 v1.6.0 v1.7.0 v1.8.0 v1.8.1 v1.8.2 v1.8.3 v1.9.0 v1.9.1
v1.10.0 v1.11.0 v1.11.1 v1.11.2 v1.11.3 v1.12.0 v1.13.0 v1.13.1
v1.13.2 v1.14.0 v1.15.0 v1.15.1 v1.16.0 v1.17.0 v1.17.1 v1.18.0

* fix(docs): add index.md symlinks for wayfinding tests

Hugo uses _index.md convention but wayfinding tests expect index.md.
Create symlinks index.md -> _index.md in docs and examples dirs.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-07-30 15:34:42 +01:00
Alexander Serheyev 8a960f327b fix(website): convert all internal links to .html for uglyURLs mode (#4858) (#4867)
* fix(website): convert /docs/overview/mcp/ link to .html for uglyURLs consistency

* fix(website): add .html suffix to single-page doc links missing it

* fix(website): replace blog short IDs with full permalink + .html

* fix: replace /blog/4 with absolute https://go-micro.dev URL in examples README

* fix(website): convert trailing-slash blog cross-references to .html

/blog/YYYY/MM/DD/slug/ → /blog/YYYY/MM/DD/slug.html across 17 files
for uglyURLs consistency. Includes roadmap blog references.

* fix(docs): add index.md symlinks for wayfinding tests

Hugo uses _index.md convention but wayfinding tests expect index.md.
Create symlinks index.md -> _index.md in docs and examples dirs.
2026-07-30 15:33:10 +01:00
Asim Aslam ebd796b352 fix(website): stop trailing-slash blog URLs serving the RSS feed (#4866)
Per-page RSS output rendered each post to <slug>/index.xml while the
post HTML rendered to <slug>.html (uglyURLs). That left the <slug>/
directory with index.xml as its only index, so requesting a post with
a trailing slash (e.g. /blog/2026/03/04/<post>/) served the XML feed
instead of a 404/the post. Drop RSS from the per-page outputs; a
per-page feed is meaningless anyway. Section and home feeds
(/blog/index.xml, /index.xml) are unaffected.

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-30 07:01:15 +01:00
Asim Aslam 26f8d75957 fix(website): space the navbar brand and link the logo to root (#4864)
The header brand hardcoded "Go</span>Micro" with no space, and the
logo linked to .Site.Home.RelPermalink which resolves to /index.html
under uglyURLs. Add the space and point the brand link at /.

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-29 11:29:55 +01:00
Asim Aslam bdd3cf9c6e fix(website): brand as "Go Micro" not "GoMicro" (#4863)
The site title, og:site_name, hero heading, PWA manifest, and package
author read "GoMicro" with no space. Add the space everywhere it
appears as a brand name.

Leaves the GoMicroToolkit Python class name in code samples untouched.

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-29 11:18:08 +01:00
Asim Aslam 8f18942525 fix(website): brand as "Go Micro" not "GoMicro" (#4862)
The site title, og:site_name, hero heading, PWA manifest, and package
author read "GoMicro" with no space. Add the space everywhere it
appears as a brand name.

Leaves the GoMicroToolkit Python class name in code samples untouched.

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-29 10:42:44 +01:00
Asim Aslam 0d53d2960a deps: bump grpc and x/text to clear reachable CVEs (#4860)
govulncheck has failed on master since ~Jul 20 on two reachable vulns,
both with upstream fixes:

- GO-2026-6061 (google.golang.org/grpc) — reachable via client/server/
  transport grpc — fixed in grpc v1.82.1 (was v1.79.3).
- GO-2026-5970 (golang.org/x/text infinite loop on invalid input),
  reachable via the http roundtripper and pgx — fixed in x/text v0.39.0
  (was v0.37.0).

go mod tidy also carried x/net v0.55.0 -> v0.56.0, protobuf, x/sys,
x/tools, and genproto forward. `govulncheck ./...` now reports zero
reachable vulnerabilities; grpc client/server/transport tests pass.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-29 09:32:23 +01:00
Asim Aslam f7943dfe0d website: fix broken docs — leaf-bundle conflict, ugly URLs, front matter (#4861)
The migrated docs (#4858) 404'd for every page (e.g. /docs/getting-started.html)
and rendered untitled. Three Jekyll-to-Hugo migration gaps:

1. Leaf-bundle conflict: content/en/docs (and examples, examples/realworld,
   guides/migration) had BOTH index.md and _index.md. index.md makes a
   directory a leaf bundle — terminal — so every sibling page became a
   non-rendered resource with no URL. Merged each index.md's (richer) body
   into its _index.md and removed index.md, so the sections render children.

2. URL scheme: the old Jekyll site (and every inbound link, bookmark, and
   in-content link) uses .html paths. Set uglyURLs: true so pages serve at
   .html again — /docs/getting-started.html resolves instead of 404ing.

3. Front matter: 61 doc pages were raw Jekyll (`layout: default` or none),
   so Docsy rendered them titleless with a broken sidebar. Derived each
   title from its H1, wrote proper Hugo front matter, dropped `layout`.

Also removed content/en/docs/search.md — a Jekyll Liquid page ({% assign
… | where_exp %}) that hard-failed the Hugo build; Docsy ships its own
search.

Verified with a full local Hugo Extended 0.164.0 build (PostCSS installed):
builds clean, 26+ doc pages emit at .html, titles/H1 populate, and the
sidebar lists 24 doc pages.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-29 09:32:11 +01:00
Asim Aslam a2316dbe4f website: build at canonical root baseURL, not the Pages subpath (#4859)
The Hugo/Docsy site (#4858) rendered unstyled live. go-micro.dev is an
nginx proxy that maps `/` to micro.github.io/go-micro/, but the deploy
workflow built with `--baseURL "${{ steps.pages.outputs.base_url }}/"`,
which for this project repo is https://micro.github.io/go-micro/. That
prefixes every asset and link with /go-micro/, so through the proxy the
stylesheet resolves to go-micro.dev/go-micro/scss/... which maps to
micro.github.io/go-micro/go-micro/scss/... and 404s — no CSS.

Verified: the CSS is 200 at micro.github.io/go-micro/scss/...; the baked
/go-micro/ path 404s through the proxy; the root path (this fix) is 200.

Build at the canonical root baseURL (https://go-micro.dev/, already in
hugo.yaml) so assets are /scss/... — which the proxy maps correctly. This
matches how the old Jekyll site was configured (baseurl: "").


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-29 09:12:53 +01:00
Asim Aslam 2d4af36ac8 docs: migrate website to Hugo and Docsy (#4858)
Co-authored-by: Codex <codex@openai.com>
2026-07-29 08:42:34 +01:00
Asim Aslam 9d306dcfc1 Update README with overview and community sections
Run Tests / Unit Tests (push) Has been cancelled
govulncheck / govulncheck (push) Has been cancelled
Lint / golangci-lint (push) Has been cancelled
Harness (E2E) / Harnesses (mock LLM) (push) Has been cancelled
Harness (E2E) / Provider harnesses (live LLM conformance) (push) Has been cancelled
Run Tests / Etcd Integration Tests (push) Has been cancelled
Deploy Jekyll with GitHub Pages dependencies preinstalled / build (push) Has been cancelled
Deploy Jekyll with GitHub Pages dependencies preinstalled / deploy (push) Has been cancelled
Added an overview section and restructured community information in the README.
2026-07-20 11:03:53 +01:00
Asim Aslam db4401d306 client/service: rename the in-process fast-path to Local + service knob (#4855)
goreleaser / goreleaser (push) Has been cancelled
Renames the fast-path option to the cleaner Local across the stack (it's
still unreleased) and adds a service-level knob:

- client.Local() (was client.LocalDispatch) enables the in-process
  fast-path; Options.Local is the field. The internal/network package it
  dispatches through is the "local network".
- service.Local() (aliased micro.Local()) turns it on for a whole
  service's client in one place — every co-located unary call (agent tool
  calls, flow dispatch, gateway -> service) takes the fast-path, no
  per-call wiring. Same o.Client.Init(...) pattern the Broker option uses.

Off by default; a no-op for distributed deployments since the fast-path
falls back to the network for anything not co-located.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 17:02:57 +01:00
Asim Aslam 08a3edcff4 client/server: in-process dispatch fast-path (opt-in) (#4854)
When caller and callee run in the same process, a unary Call pays the
full network tax — pool.Get, dial, codec-over-socket, and the transport
pump — even though the handler table is right there. This adds an opt-in
fast-path that dispatches directly.

- internal/network: a neutral registry (transport.Message in/out) so
  client and server wire up without importing each other. A running server
  registers a dispatcher under its name on Start, deregisters on Stop.
- server: localDispatch serves a request in-process through the same
  router (identical wrappers/codecs/error mapping) over an in-memory
  socket — no dial, no pipe, no gob.
- client: LocalDispatch() opt-in. In call(), a unary request whose body and
  response are raw frames (codec/bytes.Frame — the agent/MCP/flow shape)
  dispatches locally; everything else falls back to the network path
  unchanged.

Correctness test proves the fast-path returns byte-identical replies to
the network path; benchmark shows ~545µs -> ~28µs (~20x) and ~3.6x fewer
allocations. Off by default. Covers #4817 (path b); the zero-copy typed
path remains a follow-up.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 16:41:10 +01:00
Asim Aslam 1250d33f86 deploy/kubernetes: dependency-light reconcile core (alpha) (#4853)
Adds Reconcile(desired, observed) — the pure decision an operator's
reconcile loop runs: given a desired Agent/Service/Flow resource and the
observed cluster state, it returns the one action to converge (create /
update / noop) plus Ready/Error status conditions.

No controller-runtime, no client-go: the decision is a pure function of
desired + observed, so it's fully unit-testable without a cluster. A
future operator binary supplies Observed from the live cluster and applies
the Action; only that adapter needs the Kubernetes client — keeping the
heavy dependency out of the core module.

Covers #4842 (Option B). Tests: create-when-absent, noop-when-matched-and-
ready, update-on-drift, progressing-when-under-replicated, error-on-invalid
-spec.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 15:12:20 +01:00
Asim Aslam 7e2346b8c8 flow: human-in-the-loop pause/resume (durable workflow, stage A) (#4852)
Adds a waiting run state so a flow step can suspend for external input
and resume durably — stage A of the durable-agentic-workflow design in
#4816.

- flow.Await(key, prompt) / flow.AwaitStep(...): a StepFunc that suspends
  the run. runFrom recognizes the signal, checkpoints the run with status
  "waiting" (recording what it awaits), and returns cleanly — a suspend is
  not a failure, and it is not retried or graded.
- Flow.ResumeWith(ctx, runID, input): completes the awaited step with the
  injected input (which becomes that step's output state) and continues
  from the next step.
- Flow.Waiting(ctx): lists suspended runs with their Await metadata.
- ResumePending/Pending skip waiting runs — they need input, not a
  restart. Existing crash-resume (Resume) is unchanged.

Additive: no signature or default-behavior changes. Await ergonomics
(sentinel-return) are the default proposed in #4816; open to AwaitStep-kind
instead if preferred.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 14:08:27 +01:00
Asim Aslam 6733d0c7c4 a2a: verify inbound AP2 mandates into the paid path (opt-in) (#4851)
The AP2 primitives (checkout/payment mandates, Ed25519 sign/verify, the
x402 rail reference, attach-to-message) already existed, but the gateway
only *carried* mandates on the resulting task — it never verified them, so
ap2Verifications was never populated and a downstream paid path had no
trust signal.

Wire opt-in verification: set Options.AP2PublicKey (gateway) or
a2a.WithAP2PublicKey (embedded handler) and each mandate carried on a task
is verified (signature + task/context binding) with the result recorded in
task.AP2Verifications; the x402 settlement rail rides along for the paid
path. Off by default — mandates stay carried-but-unverified — so no payment
trust decision enters the default flow.

Adds a gateway integration test driving a real message/send that carries a
signed x402 payment mandate (verified, rail carried; tampered → surfaced as
unverified) plus a default-path test proving carry-only is unchanged.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 13:10:00 +01:00
Asim Aslam bbeb3ac920 a2a: guard push-notification callbacks against SSRF (#4849)
The A2A gateway's push-notification flow (tasks/pushNotificationConfig/set
→ deliverPush) POSTed task state to a caller-supplied URL via the default
HTTP client, so an untrusted A2A caller could aim the gateway at internal
addresses (loopback, link-local cloud metadata, RFC1918) it would
otherwise never reach — a server-side request forgery vector (#4129).

Add a default SSRF-safe policy: only http/https callbacks whose host does
not resolve to a loopback, private, link-local, multicast, or unspecified
address. It's enforced when the config is set (caller gets a clear
rejection, nothing stored) and again at delivery, and the delivery client
re-checks the resolved IP at dial time so a name that passes validation
can't be rebound to an internal address before connect.

Operators that need a trusted in-cluster receiver set Options.AllowPushURL
(gateway) or a2a.WithPushURLPolicy (embedded handlers) to own the policy;
that path skips the built-in private-IP dial guard by design.

Tests cover blocked/allowed URLs, the dial-time guard, set-time rejection,
default-deny delivery, and the operator override.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-15 12:20:36 +01:00
Asim Aslam c5962944a4 docs: add Go Micro vs Dapr comparison (#4850)
Co-authored-by: Codex <codex@openai.com>
2026-07-15 11:45:08 +01:00
Asim Aslam aaa03f89e3 deploy/kubernetes: embed CRDs instead of duplicating them (#4845)
goreleaser / goreleaser (push) Has been cancelled
The CRD manifests were kept in two places — real YAML under config/crd/
(for kubectl apply) and byte-identical const strings in manifests.go
(for the Go CRDManifests map) — which will silently drift.

Make config/crd/*.yaml the single source of truth and go:embed it;
CRDManifests now reads the embedded bytes. Drops ~120 lines of
duplicated YAML, no behavior change (still stdlib-only, tests unchanged).


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 16:53:53 +01:00
Asim Aslam 1f5ae1f39a loop: pause automatic runs while we do focused fixes (#4843)
Comment out the automatic triggers on every loop workflow so the
autonomous engine stops firing on its own while we land the current
round of fixes 1:1:

- planner / builder / coherence / security / release: drop the cron
  schedules (no more hourly/daily/weekly runs, no nightly auto-release).
- triage: drop the workflow_run trigger so CI failures no longer
  auto-dispatch agent tasks.

Each keeps workflow_dispatch, so any loop can still be run on demand,
and re-enabling is just uncommenting the trigger. No prompts, tokens, or
logic changed — only when the workflows fire.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 13:29:33 +01:00
Asim Aslam 6950870dd9 a2a: conform to external A2A clients — well-known path + spec SSE events (#4832)
* a2a: conform to external A2A clients — well-known path + spec SSE events

The A2A gateway interoperated go-micro-to-go-micro but a real external
client (ADK, LangGraph, a2a-SDK) would not:

- Discovery: served the Agent Card at /.well-known/agent.json, but A2A
  0.3.0 discovers it at /.well-known/agent-card.json. Serve both, with
  agent-card.json canonical and agent.json a legacy alias — per-agent,
  per-skill, and at the single-agent top level.

- message/stream emitted repeated full Task snapshots. External SSE
  clients parse by `kind` and stop on `final:true`; a Task snapshot has
  neither, so they never terminate. Emit spec-shaped TaskArtifactUpdate
  (append) chunks and close with a TaskStatusUpdate final:true. The
  non-streaming and resubscribe paths also close with a terminal marker.

- A streaming error set both `result` and `error` in one JSON-RPC
  response (strict clients reject it). Emit a failed status-update
  instead — never result and error together.

Tests assert the canonical card path, the status-update/artifact-update
event shapes ending in final:true, and that no response carries both
result and error.

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

* harness: update a2a-streaming to the spec-shaped stream events

The A2A gateway now emits artifact-update deltas and a terminal
status-update (final:true) instead of repeated full Task snapshots, so
the conformance harness must reassemble the answer from the append
artifact-update chunks and assert the final:true marker. This makes the
harness a stronger spec check rather than a snapshot-shape check.

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

* agent: update a2a stream test to spec-shaped events

TestA2AStreamUsesAgentChatPathWithTools decoded the last SSE event as a
completed Task snapshot with artifacts. The gateway now closes the stream
with a status-update (final:true) and carries the answer as append
artifact-update deltas, so reassemble the answer from those deltas and
assert the terminal completed status-update instead.

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-07-12 13:27:27 +01:00
Asim Aslam 36f80386f1 loop: refresh priorities after shipped capability (#4844)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 13:27:18 +01:00
Asim Aslam b5df7e0a71 Add Kubernetes CRD foundation (#4839)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 13:01:09 +01:00
Asim Aslam 7e3d2d3b13 x402: harden spend cap — reject invalid amounts, require settler option (#4831)
Two spend-safety fixes from the gap audit (#4814):

- Client.Do refused a 402 only on the budget check, but parsed
  maxAmountRequired with a swallowed error, so a non-decimal, overflowing
  or negative amount became 0 and passed the cap trivially while Payer.Pay
  still signed against the string. Now reject any amount that is not a
  positive integer before signing.

- Require settled only when the facilitator implemented Settler; a
  verify-only facilitator served the resource while no funds moved. Add
  Config.RequireSettlement to fail closed in that case.

Tests cover invalid/negative/overflow amounts and the verify-only
fail-closed path.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 12:40:12 +01:00
Asim Aslam 3e4b13e2bd Fix grpcreflect JSON name lint (#4826)
* gateway/mcp: expose reflected gRPC services

* Fix grpcreflect JSON name lint

---------

Co-authored-by: Codex <codex@openai.com>
2026-07-12 11:28:53 +00:00
Asim Aslam 1b83cdff9c mcp: stdio/ws tool results are JSON + isError (fixes garbage to Claude Desktop) (#4825)
Closes #4813. The stdio transport is the path an external MCP host (Claude
Desktop) uses, and it emitted broken output:
- tool results were `fmt.Sprintf("%v", decodedJSON)` → Go map-syntax
  (`map[id:1 name:bob]`), not JSON. Now returned as JSON text.
- tool-execution failures were returned as JSON-RPC protocol errors; per the
  MCP spec they must be a result with `isError:true` so the agent can read the
  failure. Now they are (span/audit still record the error).

Both fixes are shared between stdio and websocket via a new `mcpToolResult`/
`mcpToolError` (dedupes the two transports). Added the missing stdio round-trip
tests (the package had zero) proving JSON output and the isError contract, using
an injected fake client; updated the websocket auth tests that asserted the old
protocol-error-on-tool-failure behavior.

Also fixes a pre-existing golangci-lint failure on master (unnecessary
`string(...)` conversion in grpcreflect.go from #4821) so the mcp package lints
clean — another one the required-checks gap let through.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 12:28:06 +01:00
Asim Aslam 3ef265f3c2 loop: refresh planner priorities after gRPC MCP (#4828)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 12:27:04 +01:00
Asim Aslam e8977cf335 gateway/mcp: expose reflected gRPC services (#4821)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 12:09:31 +01:00
Asim Aslam c6ab16f3bf loop: drop shipped x402 buyer priority (#4818)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 11:44:34 +01:00
Asim Aslam f93f3c6045 examples: add x402 buyer agent (#4811)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 11:20:25 +01:00
Asim Aslam 9b4b3ce827 loop: drop completed spend observability priority (#4808)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 10:36:04 +01:00
Asim Aslam 4d6ebe1fd3 Observe agent x402 spend (#4806)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 10:23:30 +01:00
Asim Aslam 26ab5a3bf0 loop: drop completed x402 buyer priority (#4804)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 09:53:05 +01:00
Asim Aslam d584d372cd agent: wire x402 payer into tool runtime (#4802)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 09:29:36 +01:00
Asim Aslam 521aff145f Refresh planner queue after closed items (#4799)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 08:55:28 +01:00
Asim Aslam eafa186894 docs: refresh coherence changelog (#4798)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 08:51:49 +01:00
Asim Aslam 91c57663cc roadmap: drop the word "bets" (development, not bets) (#4792)
Per standing preference — this is planned development/capability, not "bets".
Reword ROADMAP.md and .github/loop/PRIORITIES.md accordingly; no change to what
the loop builds.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 08:39:14 +01:00
Asim Aslam cb49c1c2d8 Add Gemini streaming support (#4793)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 08:37:50 +01:00
Asim Aslam db31341b30 roadmap: restock with capability bets; repoint the loop queue (#4790)
The last-100-commit assessment found the loop producing busy-work — but the root
cause was the roadmap: every forward item was hardening/conformance/docs-polish,
no net-new capability. The loop was faithfully executing a maintenance backlog.

Restock the roadmap with real capability bets and demote maintenance to explicit
background:
- Now: agents that pay (wire the existing x402 buyer into the agent runtime);
  AP2 mandate foundation over A2A+x402 (#3552).
- Next: gRPC-reflection MCP; Kubernetes operator + CRDs.
- Later: the runtime-fitness loop (live Mu + operator/canary); HTTP/3; A2A
  reconnection; memory/RAG.
- Ongoing: hardening/conformance/DX, capped so it never crowds out capability.

Repoint .github/loop/PRIORITIES.md to rank the capability bets at the top, with
the flagship decomposed into buildable issues (#4786 buyer wiring, #4787 spend
observability, #4788 example), so the loop pulls real work instead of grooming
itself.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-12 08:20:32 +01:00
Asim Aslam a583d5741d Refresh planner queue after provider inspection (#4785)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 08:06:27 +01:00
Asim Aslam c9e61c0f7b Classify provider failures in agent inspection (#4782)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 06:49:13 +01:00
Asim Aslam 39f8aee34d Refresh planner queue after retry controls (#4778)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 06:13:40 +01:00
Asim Aslam 7f9096a1cd Add model retry jitter control (#4775)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 04:56:39 +01:00
Asim Aslam b6ad784b67 Refresh planner priority after memory compaction (#4772)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 04:06:28 +01:00
Asim Aslam a662bcff9d Expose compacted memory summaries (#4769)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 03:28:48 +01:00
Asim Aslam 482d3e7d69 Refresh planner queue after chat streaming (#4766)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 02:45:46 +01:00
Asim Aslam 5aa6e50ae5 Stream remote agent chat replies (#4763)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 02:15:11 +01:00
Asim Aslam b2369885bb Refresh planner queue after input resume (#4761)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 01:42:36 +01:00
Asim Aslam 741f308546 Add CLI input resume for agent runs (#4758)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 00:59:29 +01:00
Asim Aslam 5e49464323 Refresh planner queue after cancellation work (#4756)
Co-authored-by: Codex <codex@openai.com>
2026-07-12 00:27:22 +01:00
Asim Aslam 3995ed906e agent: propagate stream run context (#4753)
goreleaser / goreleaser (push) Has been cancelled
Co-authored-by: Codex <codex@openai.com>
2026-07-11 23:57:43 +01:00
Asim Aslam ef5d2fb94f Refresh planner queue after x402 guardrail (#4751)
Co-authored-by: Codex <codex@openai.com>
2026-07-11 23:19:09 +01:00
Asim Aslam 2293aafc5d Add agent x402 spend budget guardrail (#4748)
Co-authored-by: Codex <codex@openai.com>
2026-07-11 23:05:54 +01:00
Asim Aslam c0fadaecd2 Refresh planner queue after streaming conformance (#4744)
Co-authored-by: Codex <codex@openai.com>
2026-07-11 22:24:06 +01:00
Asim Aslam b787755a00 Add A2A streaming conformance harness (#4741)
Co-authored-by: Codex <codex@openai.com>
2026-07-11 22:04:43 +01:00
Asim Aslam 3dc0369302 Refresh planner queue after pgx migration (#4739)
Co-authored-by: Codex <codex@openai.com>
2026-07-11 21:28:51 +01:00
Asim Aslam 585f18153c Migrate postgres pgx store to pgx v5 (#4736)
Co-authored-by: Codex <codex@openai.com>
2026-07-11 21:03:54 +01:00
Asim Aslam 9233bc738d Refresh planner queue after plan delegate coverage (#4734)
Co-authored-by: Codex <codex@openai.com>
2026-07-11 20:36:55 +01:00
393 changed files with 15528 additions and 4374 deletions
+1 -2
View File
@@ -1,2 +1 @@
github: asim
custom: ["https://go-micro.dev/support"]
github: micro
+33 -20
View File
@@ -1,28 +1,41 @@
# Priorities
The ranked work queue for the autonomous improvement loop. The
**architecture-review** pass (the *architect*) owns this file: each run it turns
the [roadmap](../../ROADMAP.md) plus an internal scan (gaps in the
services → agents → workflows lifecycle, API coherence, drift, tech debt, test and
DX friction) into a single ordered list — highest-value first — and links each
item to a tracking issue. The hourly **continuous-improvement** pass works the
**top item whose issue is still open**. So the architect decides *what*, and the
increment loop *builds* it.
The ranked work queue for the autonomous improvement loop. The **planner** owns
this file: each run it turns the [roadmap](../../ROADMAP.md) plus an internal scan
into a single ordered list — highest-value first — each item linked to a tracking
issue. The **builder** works the top item whose issue is still open. So the
planner decides *what*, the builder *builds* it.
**Reading / editing.** An item is done when its linked issue closes (the increment
that builds it adds `Closes #<issue>`). Roadmap phase (Now → Next → Later) is the
primary ordering; internal findings are interleaved by value, not kept in a
separate list. The human can reorder this list — or the issues — at any time to
redirect the loop; direction always wins.
**Bias to capability, not busy-work.** The top of this queue is net-new capability
from the roadmap's *Now/Next* items. Hardening/conformance/DX polish is background
work (roadmap *Ongoing*) — kept low here and capped, never allowed to crowd out
capability. If an area has had several increments with no user-visible gain, it is done
for now; rank real-headroom capability instead.
**Off-limits to the loop** (the architect proposes these as notes, never as queue
items the loop can auto-merge): brand/positioning copy, breaking public-API
changes, architectural rewrites. Those go to the human.
**Reading / editing.** An item is done when its linked issue closes (the PR that
builds it adds `Closes #<issue>`). The human can reorder this list or the issues at
any time — direction always wins.
**Off-limits to the loop** (planner proposes as notes, never auto-merged queue
items): brand/positioning copy, breaking public-API changes, architectural
rewrites.
## Work queue (ranked)
1. **Gate mock provider plan-delegate resume scenarios** ([#4713](https://github.com/micro/go-micro/issues/4713)) — #4709 closed the live AtlasCloud nested tool-call rejection gap and #4725 closed the website first-agent wayfinding gap, so the highest-value remaining Now work is deterministic no-secret agent-loop coverage. Completed plan steps, notifications, unsafe fallback parsing, and resume semantics must stay stable without provider keys before broadening into live-provider conformance.
2. **Migrate store/postgres from pgx/v4 to pgx/v5** ([#4556](https://github.com/micro/go-micro/issues/4556)) — Security upkeep matters to the service-framework half of the harness, and #4556 is the remaining open enhancement/security item. Keep it below the agent-loop contract because it is narrower than the current developer-adoption goal, but do not let reachable dependency risk drift indefinitely.
### Capability — the headline (roadmap: Now / Next)
_Seeded by Claude Code from the roadmap + open issues; thereafter maintained by the
architecture-review pass._
1. **A2A external-client conformance** ([#4815](https://github.com/micro/go-micro/issues/4815)) — make the gateway easier for non-go-micro agents to discover and stream from by serving the well-known agent card path and spec SSE events.
2. **AP2 mandate foundation for agent payments** ([#4841](https://github.com/micro/go-micro/issues/4841)) — add opt-in checkout/payment mandate signing and verification so A2A-carried payment authority can settle over x402 without changing defaults.
3. **Kubernetes CRD reconciler foundation** ([#4842](https://github.com/micro/go-micro/issues/4842)) — turn the shipped alpha `Agent`, `Service`, and `Flow` CRDs into a minimally runnable native deployment path with workload reconciliation and status conditions.
### In flight — do not re-queue
_None right now._
### Background — hardening & DX (roadmap: Ongoing; capped)
_Background hardening is intentionally empty right now. Recent work covered first-agent
wayfinding, plan/delegate recovery, provider fallback repair, streaming, memory
compaction, retry controls, provider-failure inspection, x402 buyer safety, gRPC-reflection MCP,
MCP result conformance, and the alpha Kubernetes CRD surface. Further churn in those
areas should be marked `needs-human` unless it unlocks a clear user-visible capability._
+2 -1
View File
@@ -33,6 +33,7 @@ jobs:
harness:
name: Harnesses (mock LLM)
runs-on: ubuntu-latest
if: github.event_name != 'schedule' || github.repository == 'micro/go-micro'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
@@ -51,7 +52,7 @@ jobs:
# 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'
if: (github.event_name == 'schedule' && github.repository == 'micro/go-micro') || github.event_name == 'workflow_dispatch'
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
+5 -2
View File
@@ -14,8 +14,11 @@ name: "Loop: Builder"
on:
workflow_dispatch: {}
schedule:
- cron: "29 * * * *"
# PAUSED 2026-07-12: automatic schedule disabled while the team does focused
# 1:1 fixes. Still runnable on demand via workflow_dispatch. Re-enable by
# uncommenting the schedule below.
# schedule:
# - cron: "29 * * * *"
permissions:
issues: write
+5 -2
View File
@@ -14,8 +14,11 @@ name: "Loop: Coherence"
on:
workflow_dispatch: {}
schedule:
- cron: "0 7 * * *"
# PAUSED 2026-07-12: automatic schedule disabled while the team does focused
# 1:1 fixes. Still runnable on demand via workflow_dispatch. Re-enable by
# uncommenting the schedule below.
# schedule:
# - cron: "0 7 * * *"
permissions:
issues: write
+5 -2
View File
@@ -14,8 +14,11 @@ name: "Loop: Planner"
on:
workflow_dispatch: {}
schedule:
- cron: "59 * * * *"
# PAUSED 2026-07-12: automatic schedule disabled while the team does focused
# 1:1 fixes. Still runnable on demand via workflow_dispatch. Re-enable by
# uncommenting the schedule below.
# schedule:
# - cron: "59 * * * *"
permissions:
issues: write
+5 -2
View File
@@ -12,8 +12,11 @@ name: "Loop: Release"
on:
workflow_dispatch: {}
schedule:
- cron: "0 23 * * *"
# PAUSED 2026-07-12: automatic nightly release disabled while the team does
# focused 1:1 fixes. Cut a release on demand via workflow_dispatch. Re-enable
# by uncommenting the schedule below.
# schedule:
# - cron: "0 23 * * *"
permissions:
contents: read
+5 -2
View File
@@ -14,8 +14,11 @@ name: "Loop: Security"
on:
workflow_dispatch: {}
schedule:
- cron: "0 6 * * 1"
# PAUSED 2026-07-12: automatic schedule disabled while the team does focused
# 1:1 fixes. Still runnable on demand via workflow_dispatch. Re-enable by
# uncommenting the schedule below.
# schedule:
# - cron: "0 6 * * 1"
permissions:
issues: write
+7 -3
View File
@@ -7,9 +7,13 @@ name: "Loop: Triage"
# failures become fixes with no human in the middle. Gated on CODEX_TRIGGER_TOKEN.
on:
workflow_run:
workflows: ["Harness (E2E)", "Lint", "Run Tests", "govulncheck"]
types: [completed]
workflow_dispatch: {}
# PAUSED 2026-07-12: automatic CI-failure dispatch disabled while the team
# does focused 1:1 fixes, so failures don't auto-spawn agent tasks. Re-enable
# by uncommenting the workflow_run trigger below.
# workflow_run:
# workflows: ["Harness (E2E)", "Lint", "Run Tests", "govulncheck"]
# types: [completed]
permissions:
issues: write
+46 -17
View File
@@ -1,45 +1,74 @@
# Sample workflow for building and deploying a Jekyll site to GitHub Pages
name: Deploy Jekyll with GitHub Pages dependencies preinstalled
name: Deploy Hugo site to GitHub Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["master"]
# Allows you to run this workflow manually from the Actions tab
pull_request:
paths:
- "internal/website/**"
- ".github/workflows/website.yml"
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
env:
HUGO_VERSION: "0.164.0"
jobs:
# Build job
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: internal/website
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Build with Jekyll
uses: actions/jekyll-build-pages@v1
with:
source: ./internal/website
destination: ./_site
- name: Upload artifact
fetch-depth: 0
- name: Setup Pages
id: pages
uses: actions/configure-pages@v5
- name: Setup Hugo
uses: peaceiris/actions-hugo@v3
with:
hugo-version: ${{ env.HUGO_VERSION }}
extended: true
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version-file: internal/website/.nvmrc
cache: npm
cache-dependency-path: internal/website/package-lock.json
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: stable
cache-dependency-path: internal/website/go.sum
- name: Install frontend dependencies
run: npm ci
- name: Build site
# go-micro.dev is served by an nginx proxy that maps `/` to
# micro.github.io/go-micro/ (see the deploy nginx.conf). The site must
# therefore be built at its canonical ROOT baseURL — not the Pages
# project subpath from configure-pages (https://micro.github.io/go-micro/).
# Building at the subpath prefixes every asset/link with /go-micro/, which
# becomes /go-micro/go-micro/ through the proxy and 404s, leaving the site
# unstyled. hugo.yaml already declares baseURL: https://go-micro.dev/.
run: hugo --gc --minify --baseURL "https://go-micro.dev/"
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v3
with:
path: internal/website/public
# Deployment job
deploy:
if: github.event_name != 'pull_request'
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
+41
View File
@@ -18,15 +18,56 @@ below is kept current between tags and rolled into the next version when it ship
## [Unreleased]
### Added
- **Gemini streaming support** — the Gemini provider now supports streaming model responses. (`ai/gemini/`)
- **Model retry jitter controls** — model retry behavior can now use jitter controls to reduce synchronized retry bursts. (`ai/`, `agent/`)
- **Compacted memory summaries** — agent memory now exposes compacted run summaries for easier inspection and recovery. (`agent/`)
- **CLI input resume for agent runs** — the CLI can resume agent runs that require additional user input. (`cmd/micro/`, `agent/`)
- **A2A inbound AP2 mandate verification (opt-in)** — set `Options.AP2PublicKey` (or `a2a.WithPushURLPolicy`'s sibling `a2a.WithAP2PublicKey` for embedded handlers) and the gateway verifies AP2 payment/checkout mandates carried on incoming messages — signature and task/context binding — recording the outcome in each task's `ap2Verifications`, with the x402 settlement rail carried through for the paid path. Off by default; mandates are otherwise carried unverified. (`gateway/a2a/`)
- **Flow human-in-the-loop pause/resume** — a flow step can suspend a run for external input with `flow.Await(key, prompt)` (or `flow.AwaitStep`): the run checkpoints with status `waiting` and `Execute` returns cleanly. `Flow.Waiting` lists suspended runs with what they await, and `Flow.ResumeWith(ctx, runID, input)` injects the input and continues from the next step. Recovery (`ResumePending`) skips waiting runs since they need input, not a restart. (`flow/`)
- **Kubernetes reconcile core (alpha)** — `kubernetes.Reconcile(desired, observed)` decides the single action needed to converge an `Agent`/`Service`/`Flow` resource toward its Deployment (create / update / noop) and returns `Ready`/`Error` status conditions. Dependency-free (no controller-runtime / client-go) and fully unit-testable; a future operator binary supplies observed state and applies the action. (`deploy/kubernetes/`)
- **In-process "local network" fast-path (opt-in)** — `client.Local()` lets a unary `Call` to a service running in the same process skip the network transport and dispatch straight to that server's handlers (for raw `codec/bytes.Frame` bodies — the shape agent/MCP/flow tool calls use), running the same router, wrappers, and codecs. In a benchmark this cut an in-process call from ~545µs to ~28µs (≈20×) with ~3.6× fewer allocations. Off by default; falls back to the network path for anything it doesn't cover. (`client/`, `server/`, `internal/network/`)
- **`micro.Local()` service option** — turn on the in-process fast-path for a whole service in one place: every co-located unary call its client makes (agent tool calls, flow dispatch, gateway → service) takes the fast-path, with no per-call wiring. Off by default; a no-op for distributed deployments. (`service/`, root `options.go`)
### Changed
- **Remote agent chat streaming** — `micro chat` now streams replies from remote agents instead of waiting for the full response. (`cmd/micro/`, `agent/`)
- **A2A external-client conformance** — the A2A gateway now serves the Agent Card at the spec 0.3.0 `/.well-known/agent-card.json` (keeping `/.well-known/agent.json` as a legacy alias), and `message/stream` emits spec-shaped `status-update`/`artifact-update` events ending in a `final:true` status-update instead of repeated full `Task` snapshots — and never sends `result` and `error` together. Standard A2A clients (ADK, LangGraph, a2a-SDK) can now discover and stream from go-micro agents. (`gateway/a2a/`)
### Fixed
- **Provider failure inspection metadata** — provider failures recorded during agent runs now retain classification metadata for inspection. (`agent/`, `ai/`)
### Security
- **x402 spend-cap hardening** — the paying `Client` now refuses a 402 whose `maxAmountRequired` is not a positive integer (a swallowed parse error or negative amount previously bypassed the budget cap), and a new `Config.RequireSettlement` fails closed when a paid request is served by a verify-only facilitator that never captures funds. (`wrapper/x402/`)
- **A2A push-notification SSRF guard** — the A2A gateway no longer delivers task push notifications to caller-supplied URLs that resolve to loopback, private, link-local (incl. cloud metadata), or unspecified addresses. Callbacks are validated when set and re-checked at dial time on the resolved IP (DNS-rebinding safe); non-http(s) schemes are rejected. `Options.AllowPushURL` (and `a2a.WithPushURLPolicy` for embedded handlers) lets operators authorize trusted in-cluster receivers. (`gateway/a2a/`)
---
## [6.7.0] - July 2026
### Added
- **A2A streaming conformance harness** — A2A streaming behavior is now covered by focused conformance checks. (`gateway/a2a/`, `internal/harness/`)
- **Agent x402 spend budget guardrail** — agents now have spend budget guardrails for x402-paid tool calls. (`agent/`, `gateway/`)
- **First-agent chat/inspect fixture** — the maintained first-agent CLI fixture now covers chat and inspect boundaries together. (`internal/harness/`, `cmd/micro/`)
- **Zero-to-hero inspect transcript check** — the 0→hero harness now verifies the inspect transcript path stays visible in the lifecycle walkthrough. (`internal/harness/zero-to-hero-ci/`, `internal/website/docs/`)
### Changed
- **Agent stream run context propagation** — agent streams now preserve run context through streaming paths for more complete tracing and inspection. (`agent/`)
- **Postgres store pgx v5 migration** — the Postgres store now uses pgx v5. (`store/postgres/`, `go.mod`)
- **Plan-delegate plan persistence** — plan/delegate runs now persist plan state more defensively across harness scenarios. (`agent/`, `internal/harness/`)
### Fixed
- **Nested tool-call markup rejection** — agent argument parsing now rejects nested tool-call markup instead of accepting ambiguous tool input. (`agent/`)
- **Retry cancellation during backoff** — retry backoff now respects cancellation more reliably. (`agent/`, `ai/`)
- **Plan-delegate mock recovery regression gate** — the harness now catches plan/delegate mock recovery regressions before they ship. (`internal/harness/`, `agent/`)
- **First-agent fixture registration wait** — first-agent fixture registration is less race-prone during harness runs. (`internal/harness/`)
- **Memory stream Nack ordering** — memory stream Nack handling now preserves ordering more reliably. (`broker/memory/`)
- **Zero-to-hero fixture output race** — 0→hero fixture output is less race-prone during harness runs. (`internal/harness/zero-to-hero-ci/`)
### Documentation
- **First-agent quickcheck wayfinding** — public docs now keep the quickcheck path discoverable from the first-agent route. (`README.md`, `internal/website/docs/`)
- **Ordered 0→hero transcript** — docs and harness checks now keep the 0→hero transcript order explicit. (`internal/website/docs/`, `internal/harness/`)
- **First-agent debug breadcrumbs** — docs now surface the first-agent debug smoke path more clearly. (`internal/website/docs/`)
- **README badge cleanup** — the README no longer shows the Go Report Card badge. (`README.md`)
---
## [6.6.0] - July 2026
+1 -1
View File
@@ -109,7 +109,7 @@ Build compelling demos showing agents interacting with go-micro services in real
- **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
- **Gateway command** - `micro gateway` (formerly `micro server`) runs the HTTP API, dashboard, auth, and — with `--mcp-address` — the MCP gateway with production controls (rate limit, scopes, auth, audit, circuit breaker, x402). Deployed via the micro CLI image; the standalone `micro-mcp-gateway` binary was folded into it.
- **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/`)
+12 -14
View File
@@ -191,20 +191,18 @@ When reporting bugs:
## Documentation Contributions
Documentation improvements are always welcome!
Documentation improvements are always welcome! There are several ways to edit the
documentation pages:
- Fix typos and grammar
- Improve clarity
- Add missing examples
- Update outdated information
- **Fix or edit an existing page**: submit a pull request with your changes — either
directly on the site via a commit + PR, or by proposing changes from a fork of the
repository.
- **Add a new page**: create a new Markdown page under
`internal/website/content/en/docs/` and open a PR as above.
Documentation lives in `internal/website/docs/`. Preview locally with Jekyll:
```bash
cd internal/website
bundle install
bundle exec jekyll serve --livereload
```
The site is built with the Hugo engine and content lives in
`internal/website/content/en`.
For local development instructions (Hugo Extended, `npm ci`, `npm run serve`, production build), see the [internal/website README](internal/website/README.md).
## Community
@@ -223,8 +221,8 @@ Maintainers handle releases:
## Questions?
- Check [documentation](internal/website/docs/)
- Browse [examples](internal/website/docs/examples/)
- Check [documentation](internal/website/content/en/docs/)
- Browse [examples](internal/website/content/en/docs/examples/)
- Open a [question issue](.github/ISSUE_TEMPLATE/question.md)
Thank you for contributing to Go Micro! 🎉
+2 -2
View File
@@ -14,7 +14,7 @@ RUN addgroup --gid "$GID" "$GROUPNAME" \
--uid "$UID" "$USER"
ENV PATH=/usr/local/go/bin:$PATH
RUN apk --no-cache add git make curl
RUN apk --no-cache add git make curl protoc
COPY --from=golang:1.26.0-alpine /usr/local/go /usr/local/go
COPY $TARGETPLATFORM/micro /usr/local/go/bin/
@@ -23,4 +23,4 @@ COPY $TARGETPLATFORM/protoc-gen-micro /usr/local/go/bin/
WORKDIR /micro
EXPOSE 8080
ENTRYPOINT ["/usr/local/go/bin/micro"]
CMD ["server"]
CMD ["gateway"]
+16 -5
View File
@@ -2,22 +2,25 @@
Go Micro is an **agent harness** and service framework for Go.
**Community:** questions, ideas, or just want to build alongside us? [Join the Discord](https://discord.gg/G8Gk5j3uXr).
## Overview
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 the 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.
## Sponsors
<a href="https://go-micro.dev/blog/3"><img src="https://upload.wikimedia.org/wikipedia/commons/7/78/Anthropic_logo.svg" height="26" /></a>
<a href="https://go-micro.dev/blog/2026/03/04/building-the-ai-native-future-of-go-micro-with-claude.html"><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>
<a href="https://go-micro.dev/blog/2026/06/23/go-micro-joins-openai-s-codex-for-open-source.html"><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>
<a href="https://go-micro.dev/blog/2026/05/28/atlas-cloud-sponsors-go-micro-300-ai-models-one-integration.html"><img src="https://www.atlascloud.ai/logo.svg" height="26" /></a>
**Want to support Go Micro and see your logo here?** [Become a sponsor](https://discord.gg/G8Gk5j3uXr) — reach out on Discord.
## Community
Questions, ideas, or just want to build alongside us? [Join the Discord](https://discord.gg/G8Gk5j3uXr).
## Commercial Support
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).
@@ -63,6 +66,14 @@ cd helloworld
micro run
```
Prefer Docker? The `micro` image (Docker Hub `micro/micro` or GitHub Container Registry `ghcr.io/micro/go-micro`) bundles the CLI and its runtime dependencies:
```bash
docker pull micro/micro:latest # or ghcr.io/micro/go-micro:latest
docker run --rm -it micro/micro new helloworld
docker run --rm -it --network host -v "$(pwd)":/micro/helloworld micro/micro run
```
Then in another terminal:
```bash
+41 -30
View File
@@ -32,44 +32,55 @@ default.
and history, end to end.
5. Battle-tested: works across every provider, fails safely, observable.
## Now — hardening
The forward work is **net-new capability**, not more hardening. Maintenance
(conformance, resilience, DX polish) continues in the background (see *Ongoing*
below) — but it is not the roadmap. This capability work is.
- **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.
## Now — capability
## Shipped agent depth
- **Agents that pay (x402 buyer in the runtime).** The seller side ships (paid
tools via the `wrapper/x402` middleware) and the buyer `x402.Client` (a
budget-capped `Payer` that turns a `402` into pay-and-retry) exists — but an
agent can't yet *autonomously* pay for a paid tool. Wire the buyer into the
agent tool loop: a budget-capped `AgentPayer` so an agent that hits a
payment-required tool settles it within budget and retries, with the spend
gated (like `ApproveTool`) and observable in `RunInfo`/traces. This makes
go-micro a runtime for **autonomous agent commerce**. *(flagship — decomposed
into issues in the loop queue)*
- **AP2 mandate foundation** ([#3552](https://github.com/micro/go-micro/issues/3552))
— verifiable payment **mandates** (a Checkout Mandate and a Payment Mandate),
signed and attached over A2A, with the Payment Mandate naming an x402 rail. The
authorization/audit layer above A2A + x402 that positions go-micro early in the
emerging agent-payments standard (Google's AP2, standardized via FIDO).
Additive and opt-in.
- **Durable agent loop** — opt-in `Checkpoint` support lets agent `Ask` and
streaming runs persist, list pending work, and resume without replaying completed
tool calls. Human-input pauses resume through explicit input helpers.
- **Agent observability** — agent `RunInfo` now feeds OpenTelemetry spans/events
across runs, model turns, tool calls, retries, delegation lineage, and resume
checkpoints.
## Next — reach & deployment
## Next — agentic depth
- **gRPC-reflection MCP** — derive MCP tools from *any* gRPC service via server
reflection, not just go-micro-native handlers. Point the gateway at an external
gRPC service and its methods become agent tools — a large jump in what an agent
can operate.
- **Kubernetes operator + CRDs** — `Agent`, `Service`, and `Flow` as first-class
Kubernetes resources; an operator reconciles them into Deployments wired to the
registry. The production deployment story for teams already on K8s.
- **Streaming** — broaden provider-backed `ai.Stream` coverage and keep chat/A2A streaming end to end.
- **Resume operations polish** — keep improving CLI/docs breadcrumbs for finding
pending agent runs and deciding whether to call resume, resume-input, or stream
resume in production.
- **Observability hardening** — keep span attributes and run inspection coherent
across agents, flows, and gateways as more providers and workflow paths are
exercised.
## Later — exploratory
## Later
- **Runtime-fitness loop** — a persistently-running dogfood app (Mu) plus an
operator/canary loop role, so the autonomous loop evolves go-micro against
**real runtime signal** (latency, errors, cost) with canary + rollback — not
just green CI. The demand signal the loop is missing today.
- **HTTP/3 transport**; richer A2A live-stream reconnection (`tasks/resubscribe`,
`input-required` handoffs); memory management (summarization, retrieval/RAG).
- Memory management (summarization, retrieval/RAG); human-in-the-loop pause/resume;
richer A2A live-stream reconnection (`tasks/resubscribe`) and `input-required`
handoffs.
## Ongoing — hardening & DX (background, not the headline)
## Developer experience (ongoing)
- 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.
Continuous but **capped** so it never crowds out capability: cross-provider
conformance, failure/resilience (timeouts, cancellation, retry/backoff), the
0→1 and 0→hero getting-started contract, streaming/observability coherence, and a
seamless CLI inner loop (scaffold → run → chat → inspect → deploy). Real, but
maintenance — the loop should spend the majority of its cycles on the capability above,
not here.
## How it's sustained
+65 -21
View File
@@ -68,35 +68,79 @@ func TestA2AStreamUsesAgentChatPathWithTools(t *testing.T) {
t.Fatalf("stream body missing tool marker: %s", rr.Body.String())
}
var final struct {
Result struct {
Status struct {
State string `json:"state"`
} `json:"status"`
Artifacts []struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
} `json:"artifacts"`
} `json:"result"`
Error any `json:"error"`
}
// The spec-shaped stream carries the answer as append artifact-update
// deltas and closes with a completed status-update (final:true).
var (
text strings.Builder
finalState string
sawFinal bool
)
for _, line := range strings.Split(strings.TrimSpace(rr.Body.String()), "\n") {
line = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "data: "))
if line == "" {
continue
}
if err := json.Unmarshal([]byte(line), &final); err != nil {
var ev struct {
Result json.RawMessage `json:"result"`
Error any `json:"error"`
}
if err := json.Unmarshal([]byte(line), &ev); err != nil {
t.Fatalf("decode event %q: %v", line, err)
}
if ev.Error != nil {
t.Fatalf("event carried an error field: %+v", ev.Error)
}
var kind struct {
Kind string `json:"kind"`
}
_ = json.Unmarshal(ev.Result, &kind)
switch kind.Kind {
case "artifact-update":
var au struct {
Artifact struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
} `json:"artifact"`
}
_ = json.Unmarshal(ev.Result, &au)
for _, p := range au.Artifact.Parts {
text.WriteString(p.Text)
}
case "status-update":
var su struct {
Status struct {
State string `json:"state"`
} `json:"status"`
Final bool `json:"final"`
}
_ = json.Unmarshal(ev.Result, &su)
if su.Final {
sawFinal = true
finalState = su.Status.State
}
default: // opening "task" snapshot
var task struct {
Artifacts []struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
} `json:"artifacts"`
}
_ = json.Unmarshal(ev.Result, &task)
for _, a := range task.Artifacts {
for _, p := range a.Parts {
if p.Text != "" {
text.WriteString(p.Text)
}
}
}
}
}
if final.Error != nil {
t.Fatalf("final event error: %+v", final.Error)
if !sawFinal || finalState != "completed" {
t.Fatalf("want a completed final:true status-update; sawFinal=%v state=%q", sawFinal, finalState)
}
if final.Result.Status.State != "completed" {
t.Fatalf("final state = %q, want completed", final.Result.Status.State)
}
if len(final.Result.Artifacts) != 1 || len(final.Result.Artifacts[0].Parts) != 1 || !strings.Contains(final.Result.Artifacts[0].Parts[0].Text, "a2a-stream-ok") {
t.Fatalf("final artifacts = %+v, want tool marker", final.Result.Artifacts)
if !strings.Contains(text.String(), "a2a-stream-ok") {
t.Fatalf("reassembled stream text missing tool marker: %q", text.String())
}
}
+49
View File
@@ -15,7 +15,9 @@ package agent
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
@@ -81,6 +83,8 @@ type agentImpl struct {
// steps counts tool executions in the current Ask, for MaxSteps.
steps int
// spend counts reserved paid-tool spend in the current Ask, for MaxSpend.
spend int64
// calls counts identical tool calls (name+args) in the current Ask,
// for LoopLimit.
calls map[string]int
@@ -226,6 +230,9 @@ func (a *agentImpl) Ask(ctx context.Context, message string) (*Response, error)
func (a *agentImpl) Stream(ctx context.Context, message string) (ai.Stream, error) {
a.mu.Lock()
defer a.mu.Unlock()
if err := ctx.Err(); err != nil {
return nil, err
}
if a.model == nil {
a.setup()
}
@@ -233,6 +240,12 @@ func (a *agentImpl) Stream(ctx context.Context, message string) (ai.Stream, erro
if err != nil {
return nil, fmt.Errorf("discover tools: %w", err)
}
runID := uuid.New().String()
ctx = ai.WithRunInfo(ctx, ai.RunInfo{
RunID: runID,
ParentID: a.parentRunID,
Agent: a.opts.Name,
})
messages := append([]ai.Message(nil), a.mem.Messages()...)
messages = append(messages, ai.Message{Role: "user", Content: message})
stream, err := a.model.Stream(ctx, &ai.Request{
@@ -244,10 +257,44 @@ func (a *agentImpl) Stream(ctx context.Context, message string) (ai.Stream, erro
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
_ = stream.Close()
return nil, err
}
a.mem.Add("user", message)
return &memoryRecordingStream{stream: stream, memory: a.mem}, nil
}
// StreamChat serves the Agent.StreamChat RPC endpoint by forwarding stream-capable
// remote clients to the agent streaming path. If the model cannot stream, the
// underlying error is returned so callers can fall back to Agent.Chat.
func (a *agentImpl) StreamChat(ctx context.Context, stream pb.Agent_StreamChatStream) error {
req, err := stream.Recv()
if err != nil {
return err
}
aiStream, err := a.streamAskAI(ctx, req.Message)
if err != nil {
return err
}
defer aiStream.Close()
for {
chunk, err := aiStream.Recv()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
if chunk == nil || chunk.Reply == "" {
continue
}
if err := stream.Send(&pb.ChatResponse{Reply: chunk.Reply, Agent: a.opts.Name}); err != nil {
return err
}
}
}
// Pending returns checkpointed agent runs that have not completed. It mirrors
// flow.Pending for startup recovery loops that drain durable agent work.
func Pending(ctx context.Context, ag Agent) ([]flow.Run, error) {
@@ -304,6 +351,7 @@ func (a *agentImpl) askLocked(ctx context.Context, runID, message, parentRunID s
a.mem.Add("user", message)
}
a.steps = 0
a.spend = 0
a.calls = map[string]int{}
a.pause = nil
@@ -352,6 +400,7 @@ func (a *agentImpl) askLocked(ctx context.Context, runID, message, parentRunID s
Timeout: a.opts.ModelTimeout,
MaxAttempts: a.opts.ModelMaxAttempts,
Backoff: a.opts.ModelRetryBackoff,
Jitter: a.opts.ModelRetryJitter,
})
if err != nil {
run.Status = agentRunFailureStatus(err)
+89
View File
@@ -5,6 +5,8 @@ import (
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
@@ -12,6 +14,7 @@ import (
codecBytes "go-micro.dev/v6/codec/bytes"
"go-micro.dev/v6/gateway/a2a"
"go-micro.dev/v6/store"
"go-micro.dev/v6/wrapper/x402"
)
// Built-in agent tools. These are not service endpoints — they are
@@ -128,9 +131,11 @@ func (a *agentImpl) toolHandler() ai.ToolHandler {
// so the result runs plan → step → loop → approve → checkpoint → base.
h := a.baseHandler()
h = a.toolTimeoutWrap(h)
h = a.x402PayWrap(h)
h = a.toolRetryWrap(h)
h = a.checkpointToolWrap(h)
h = a.approveWrap(h)
h = a.spendWrap(h)
h = a.loopWrap(h)
h = a.stepWrap(h)
h = a.planWrap(h)
@@ -172,6 +177,64 @@ func (a *agentImpl) toolTimeoutWrap(next ai.ToolHandler) ai.ToolHandler {
}
}
// x402PayWrap pays an x402 Payment Required tool result and retries the
// underlying HTTP tool once. Tools that proxy HTTP paid resources can return the
// raw x402 402 challenge body and include a "url" input; the agent then uses
// wrapper/x402.Client so payer and budget semantics stay in one place.
func (a *agentImpl) x402PayWrap(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
res := next(ctx, call)
if res.Refused != "" || !isX402Challenge(res.Content) {
return res
}
url, _ := call.Input["url"].(string)
if url == "" {
return errResult(call.ID, "x402: payment required but tool result did not include a retryable url input")
}
budget := a.opts.Budget
if budget > 0 {
remaining := budget - a.spend
if remaining <= 0 {
return refused(call.ID, ai.RefusedSpendBudget, fmt.Sprintf(
"x402 spend budget exceeded: no budget remaining for %s (spent %d of %d)",
call.Name, a.spend, budget))
}
budget = remaining
}
client := &x402.Client{Payer: a.opts.Payer, Budget: budget}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return errResult(call.ID, err.Error())
}
resp, err := client.Do(req)
if err != nil {
if strings.Contains(err.Error(), "would exceed budget") {
return refused(call.ID, ai.RefusedSpendBudget, err.Error())
}
return errResult(call.ID, err.Error())
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return errResult(call.ID, err.Error())
}
a.spend += client.Spent()
var value any
if err := json.Unmarshal(body, &value); err != nil {
value = string(body)
}
return ai.ToolResult{ID: call.ID, Value: value, Content: string(body), Attempts: 2}
}
}
func isX402Challenge(content string) bool {
var ch struct {
X402Version int `json:"x402Version"`
Accepts []x402.Requirements `json:"accepts"`
}
return json.Unmarshal([]byte(content), &ch) == nil && ch.X402Version > 0 && len(ch.Accepts) > 0
}
// toolRetryWrap retries transient tool failures with bounded backoff. It is
// opt-in because tools can have side effects; guardrail refusals and caller
// cancellation are never retried.
@@ -375,6 +438,32 @@ func (a *agentImpl) approveWrap(next ai.ToolHandler) ai.ToolHandler {
}
}
// spendWrap reserves a per-run x402 spend budget before paid tool execution.
func (a *agentImpl) spendWrap(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
amount := a.opts.ToolSpend[call.Name]
if amount <= 0 || a.opts.MaxSpend <= 0 {
return next(ctx, call)
}
if a.spend+amount > a.opts.MaxSpend {
return refused(call.ID, ai.RefusedSpendBudget, fmt.Sprintf(
"x402 spend budget exceeded: paying %d for %s would exceed per-run budget (spent %d of %d)",
amount, call.Name, a.spend, a.opts.MaxSpend))
}
a.spend += amount
if info, ok := ai.RunInfoFrom(ctx); ok {
info.Spent = a.spend
info.ToolSpend = amount
ctx = ai.WithRunInfo(ctx, info)
}
res := next(ctx, call)
if res.Refused != "" || toolErrorMessage(res) != "" {
a.spend -= amount
}
return res
}
}
// 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 {
+5 -5
View File
@@ -846,7 +846,7 @@ func TestAgentExecutesTextToolCallFallbackAfterStructuredToolCall(t *testing.T)
Input: map[string]any{"value": "agent-conformance"},
})
return &ai.Response{
Reply: echo.Content + "\n<tool_call name=\"delegate\">{\"task\":\"summarize the conformance marker\",\"to\":\"blocked-reviewer\"}</tool_call>",
Reply: "<tool_call name=\"delegate\">{\"task\":\"summarize the conformance marker\",\"to\":\"blocked-reviewer\"}</tool_call>",
Answer: echo.Content,
ToolCalls: []ai.ToolCall{
{ID: "structured-echo-1", Name: "conformance_echo", Input: map[string]any{"value": "agent-conformance"}, Result: echo.Content},
@@ -856,7 +856,7 @@ func TestAgentExecutesTextToolCallFallbackAfterStructuredToolCall(t *testing.T)
defer func() { fakeGen = nil }()
var sawTool bool
var sawBlockedDelegate bool
var delegateCalls int
a := New(
Name("conformance-mixed-text-tool"),
Provider("fake"),
@@ -865,7 +865,7 @@ func TestAgentExecutesTextToolCallFallbackAfterStructuredToolCall(t *testing.T)
WithMemory(NewInMemory(4)),
ApproveTool(func(tool string, input map[string]any) (bool, string) {
if tool == "delegate" {
sawBlockedDelegate = true
delegateCalls++
return false, "cross-provider conformance blocks delegate side effects"
}
return true, ""
@@ -885,8 +885,8 @@ func TestAgentExecutesTextToolCallFallbackAfterStructuredToolCall(t *testing.T)
if !sawTool {
t.Fatal("structured conformance_echo did not execute")
}
if !sawBlockedDelegate {
t.Fatal("tagged text delegate fallback did not execute")
if delegateCalls != 1 {
t.Fatalf("tagged text delegate fallback calls = %d, want 1", delegateCalls)
}
if len(resp.ToolCalls) != 2 {
t.Fatalf("ToolCalls = %+v, want structured echo and text delegate", resp.ToolCalls)
+205
View File
@@ -2,12 +2,17 @@ package agent
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
"go-micro.dev/v6/wrapper/x402"
)
// toolContent runs a tool call through a handler and returns the content
@@ -91,6 +96,77 @@ func TestApproveToolDoesNotGatePlan(t *testing.T) {
}
}
func TestMaxSpendAllowsPaidToolWithinBudget(t *testing.T) {
calls := 0
a := newTestAgent(Name("paid-within-budget"),
MaxSpend(10),
ToolSpend("paid.lookup", 7),
WithTool("paid.lookup", "paid lookup", nil, func(context.Context, map[string]any) (string, error) {
calls++
return `{"ok":true}`, nil
}),
)
res := a.toolHandler()(context.Background(), ai.ToolCall{ID: "paid-1", Name: "paid.lookup", Input: map[string]any{}})
if calls != 1 {
t.Fatalf("paid tool was not executed")
}
if res.Refused != "" {
t.Fatalf("paid tool was refused: %+v", res)
}
if res.Content != `{"ok":true}` {
t.Fatalf("content = %q, want paid result", res.Content)
}
}
func TestMaxSpendRefusesPaidToolBeforePaymentWhenBudgetExceeded(t *testing.T) {
calls := 0
a := newTestAgent(Name("paid-over-budget"),
MaxSpend(5),
ToolSpend("paid.lookup", 7),
WithTool("paid.lookup", "paid lookup", nil, func(context.Context, map[string]any) (string, error) {
calls++
return `{"ok":true}`, nil
}),
)
res := a.toolHandler()(context.Background(), ai.ToolCall{ID: "paid-1", Name: "paid.lookup", Input: map[string]any{}})
if calls != 0 {
t.Fatalf("paid tool ran despite budget refusal")
}
if res.Refused != ai.RefusedSpendBudget {
t.Fatalf("Refused = %q, want %q (result %+v)", res.Refused, ai.RefusedSpendBudget, res)
}
if !strings.Contains(res.Content, "x402 spend budget exceeded") {
t.Fatalf("content = %q, want inspectable budget refusal", res.Content)
}
}
func TestMaxSpendRollsBackFailedPaidToolReservation(t *testing.T) {
calls := 0
a := newTestAgent(Name("paid-rollback"),
MaxSpend(10),
ToolSpend("paid.lookup", 7),
WithTool("paid.lookup", "paid lookup", nil, func(context.Context, map[string]any) (string, error) {
calls++
if calls == 1 {
return "", context.Canceled
}
return `{"ok":true}`, nil
}),
)
h := a.toolHandler()
first := h(context.Background(), ai.ToolCall{ID: "paid-1", Name: "paid.lookup", Input: map[string]any{}})
if first.Refused != "" || !strings.Contains(first.Content, "context canceled") {
t.Fatalf("first result = %+v, want tool error without guardrail refusal", first)
}
second := h(context.Background(), ai.ToolCall{ID: "paid-2", Name: "paid.lookup", Input: map[string]any{}})
if second.Refused != "" || second.Content != `{"ok":true}` {
t.Fatalf("second result = %+v, want reservation rollback to allow retry", second)
}
}
func TestNestedTextToolCallArgumentsAreRefused(t *testing.T) {
called := false
a := newTestAgent(Name("nested-tool-arg"),
@@ -110,3 +186,132 @@ func TestNestedTextToolCallArgumentsAreRefused(t *testing.T) {
t.Fatalf("content = %q, want nested tool-call refusal", content)
}
}
type agentMockPayer struct{ calls int }
func (p *agentMockPayer) Pay(ctx context.Context, req x402.Requirements) (string, error) {
p.calls++
return "paid", nil
}
func TestAgentPayerPaysX402ToolResultAndRetries(t *testing.T) {
paid := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(x402.PaymentHeader) == "paid" {
paid = true
_, _ = w.Write([]byte(`{"ok":true}`))
return
}
w.WriteHeader(http.StatusPaymentRequired)
json.NewEncoder(w).Encode(map[string]any{
"x402Version": x402.Version,
"accepts": []x402.Requirements{{Scheme: "exact", Network: "base", MaxAmountRequired: "7", Resource: r.URL.String(), PayTo: "0xmerchant"}},
})
}))
defer srv.Close()
payer := &agentMockPayer{}
st := store.NewMemoryStore()
a := newTestAgent(Name("x402-payer"), WithStore(st), Payer(payer), Budget(10), WithTool("paid.http", "paid http", nil, func(ctx context.Context, input map[string]any) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}))
ctx := ai.WithRunInfo(context.Background(), ai.RunInfo{RunID: "run-paid", Agent: "x402-payer"})
res := a.toolHandler()(ctx, ai.ToolCall{ID: "pay-1", Name: "paid.http", Input: map[string]any{"url": srv.URL}})
if !paid || payer.calls != 1 {
t.Fatalf("payment not made: paid=%v payer.calls=%d", paid, payer.calls)
}
if res.Content != `{"ok":true}` || res.Attempts != 2 {
t.Fatalf("result = %+v, want paid response with retry attempt", res)
}
events, err := LoadRunEvents(st, "x402-payer", "run-paid")
if err != nil {
t.Fatal(err)
}
if len(events) != 1 || events[0].Spent != 7 || events[0].ToolSpend != 7 {
t.Fatalf("spend events = %#v, want one tool event with spent/tool_spend 7", events)
}
}
func TestAgentPayerRefusesX402OverBudget(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPaymentRequired)
json.NewEncoder(w).Encode(map[string]any{
"x402Version": x402.Version,
"accepts": []x402.Requirements{{Scheme: "exact", Network: "base", MaxAmountRequired: "70", Resource: r.URL.String(), PayTo: "0xmerchant"}},
})
}))
defer srv.Close()
payer := &agentMockPayer{}
a := newTestAgent(Name("x402-over-budget"), Payer(payer), Budget(10), WithTool("paid.http", "paid http", nil, func(ctx context.Context, input map[string]any) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}))
res := a.toolHandler()(context.Background(), ai.ToolCall{ID: "pay-1", Name: "paid.http", Input: map[string]any{"url": srv.URL}})
if payer.calls != 0 {
t.Fatalf("payer called despite over-budget refusal")
}
if res.Refused != ai.RefusedSpendBudget || !strings.Contains(res.Content, "would exceed budget") {
t.Fatalf("result = %+v, want budget refusal", res)
}
}
func TestAgentPayerRequiredWithoutPayerReturnsClearError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusPaymentRequired)
json.NewEncoder(w).Encode(map[string]any{
"x402Version": x402.Version,
"accepts": []x402.Requirements{{Scheme: "exact", Network: "base", MaxAmountRequired: "7", Resource: r.URL.String(), PayTo: "0xmerchant"}},
})
}))
defer srv.Close()
a := newTestAgent(Name("x402-no-payer"), Budget(10), WithTool("paid.http", "paid http", nil, func(ctx context.Context, input map[string]any) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}))
res := a.toolHandler()(context.Background(), ai.ToolCall{ID: "pay-1", Name: "paid.http", Input: map[string]any{"url": srv.URL}})
if !strings.Contains(res.Content, "no Payer configured") {
t.Fatalf("content = %q, want no payer error", res.Content)
}
}
+8
View File
@@ -248,4 +248,12 @@ func TestCompactingMemorySummarizesAndRecallsArchivedContext(t *testing.T) {
if !sawRecall {
t.Error("model request did not recall archived matching context")
}
summary := Summary(a.mem)
if !strings.Contains(summary, "Conversation memory summary") || !strings.Contains(summary, "alpha") {
t.Fatalf("inspectable memory summary = %q, want compacted alpha summary", summary)
}
a.mem.Clear()
if summary := Summary(a.mem); summary != "" {
t.Fatalf("summary after Clear = %q, want empty", summary)
}
}
+52
View File
@@ -46,6 +46,27 @@ type MemoryRecall interface {
Recall(query string, limit int) []ai.Message
}
// MemorySummary is implemented by memory backends that expose their current
// compacted summary for inspection. It lets long-running agents make memory
// compaction observable without coupling callers to a concrete store.
type MemorySummary interface {
Summary() string
}
// Summary returns the current compacted-memory summary for m, when supported.
// It returns an empty string for memory backends that have not compacted or do
// not expose an inspectable summary.
func Summary(m Memory) string {
if m == nil {
return ""
}
summarizer, ok := m.(MemorySummary)
if !ok {
return ""
}
return summarizer.Summary()
}
// 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.
@@ -116,6 +137,7 @@ type storeMemory struct {
hist *ai.History
compaction MemoryCompaction
archive []ai.Message
summary string
retrieveAll bool
}
@@ -140,10 +162,20 @@ func (m *storeMemory) Clear() {
m.mu.Lock()
m.hist.Reset()
m.archive = nil
m.summary = ""
m.mu.Unlock()
m.save()
}
// Summary returns the latest compacted summary text, if this memory has
// compacted older turns. The returned value is safe to show in debug UIs or
// checkpoints because it is exactly the summary retained in active context.
func (m *storeMemory) Summary() string {
m.mu.Lock()
defer m.mu.Unlock()
return m.summary
}
// Recall returns archived messages whose content contains words from query.
// It is deterministic and provider-neutral: no embeddings or model calls are
// required, but semantic/vector stores can replace Memory for richer retrieval.
@@ -202,12 +234,16 @@ func (m *storeMemory) load() {
}
m.mu.Lock()
m.archive = state.Archive
m.summary = state.Summary
if m.retrieveAll && len(m.archive) == 0 {
m.archive = append(m.archive, state.Messages...)
}
for _, msg := range state.Messages {
m.hist.Add(msg.Role, msg.Content)
}
if m.summary == "" {
m.summary = currentMemorySummary(state.Messages)
}
m.mu.Unlock()
}
@@ -219,6 +255,7 @@ func (m *storeMemory) save() {
data, err := json.Marshal(memoryState{
Messages: m.hist.Messages(),
Archive: m.archive,
Summary: m.summary,
})
m.mu.Unlock()
if err != nil {
@@ -256,6 +293,7 @@ func (m *storeMemory) compact() {
if summary.Role == "" {
summary.Role = "system"
}
m.summary = fmt.Sprint(summary.Content)
m.hist.Reset()
m.hist.Add(summary.Role, summary.Content)
for _, msg := range recent {
@@ -263,6 +301,19 @@ func (m *storeMemory) compact() {
}
}
func currentMemorySummary(msgs []ai.Message) string {
for _, msg := range msgs {
if msg.Role != "system" {
continue
}
text := fmt.Sprint(msg.Content)
if strings.HasPrefix(text, "Conversation memory summary:") {
return text
}
}
return ""
}
func defaultMemorySummary(msgs []ai.Message) ai.Message {
return ai.Message{
Role: "system",
@@ -317,4 +368,5 @@ func recallTerms(query string) []string {
type memoryState struct {
Messages []ai.Message `json:"messages"`
Archive []ai.Message `json:"archive,omitempty"`
Summary string `json:"summary,omitempty"`
}
+12
View File
@@ -132,8 +132,14 @@ func TestCompactingMemoryArchivePersistsAndReloads(t *testing.T) {
m.Add("assistant", "noted")
m.Add("user", "beta budget is 7")
m.Add("assistant", "noted")
if summary := Summary(m); !strings.Contains(summary, "alpha budget is 42") {
t.Fatalf("inspectable summary = %q, want alpha budget", summary)
}
reloaded := NewCompactingMemory(st, "agent/reload/history", 3, 1)
if summary := Summary(reloaded); !strings.Contains(summary, "alpha budget is 42") {
t.Fatalf("reloaded summary = %q, want alpha budget", summary)
}
recall, ok := reloaded.(MemoryRecall)
if !ok {
t.Fatal("compacting memory should support recall")
@@ -165,8 +171,14 @@ func TestCompactingMemoryUsesCustomSummarizerAndReloadsRecall(t *testing.T) {
if len(msgs) == 0 || msgs[0].Content != "custom summary count=3" {
t.Fatalf("summary = %#v, want custom summarizer output", msgs)
}
if summary := Summary(m); summary != "custom summary count=3" {
t.Fatalf("inspectable custom summary = %q, want custom summary count=3", summary)
}
reloaded := NewCompactingMemoryWithOptions(st, "agent/custom/history", MemoryCompaction{MaxMessages: 3, KeepRecent: 1})
if summary := Summary(reloaded); summary != "custom summary count=3" {
t.Fatalf("reloaded custom summary = %q, want custom summary count=3", summary)
}
recall := reloaded.(MemoryRecall)
recalled := recall.Recall("alpha budget", 1)
if len(recalled) != 1 {
+49
View File
@@ -10,6 +10,7 @@ import (
"go-micro.dev/v6/flow"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
"go-micro.dev/v6/wrapper/x402"
"go.opentelemetry.io/otel/trace"
)
@@ -59,6 +60,9 @@ type Options struct {
// ModelRetryBackoff is the base delay between transient provider failures
// (grows exponentially per attempt when retries are enabled).
ModelRetryBackoff time.Duration
// ModelRetryJitter adds up to this random delay to each provider retry
// backoff. Default 0 preserves deterministic timing unless explicitly set.
ModelRetryJitter time.Duration
// ToolTimeout bounds each tool execution (0 disables). The timeout is
// applied before custom tools, delegate, and service RPC calls so context
// deadlines propagate consistently through the agent loop.
@@ -98,6 +102,14 @@ type Options struct {
LoopLimit int
// Approve gates each action before it runs. Nil = allow all.
Approve ApproveFunc
// MaxSpend bounds paid x402 tool spend per Ask in the asset's smallest
// unit (0 = disabled). ToolSpend lists known paid tools and their prices.
MaxSpend int64
ToolSpend map[string]int64
// Payer lets the agent settle x402 Payment Required challenges from tools.
// Budget bounds autonomous x402 payments per Ask (0 = unlimited).
Payer x402.Payer
Budget int64
// A2AAddress, if set, makes Run serve this agent over the A2A protocol
// on that address directly (no separate gateway), e.g. ":4000".
@@ -224,6 +236,37 @@ func ApproveTool(fn ApproveFunc) Option {
return func(o *Options) { o.Approve = fn }
}
// MaxSpend bounds paid x402 tool spend per Ask, in the asset's smallest unit
// (0 = disabled). A paid tool that would exceed the cap is refused before the
// tool handler runs or any payment can be made.
func MaxSpend(amount int64) Option {
return func(o *Options) { o.MaxSpend = amount }
}
// ToolSpend records the x402 price for a tool, in the asset's smallest unit,
// so MaxSpend can reserve budget before execution. Non-positive amounts are
// treated as free.
func ToolSpend(tool string, amount int64) Option {
return func(o *Options) {
if o.ToolSpend == nil {
o.ToolSpend = map[string]int64{}
}
o.ToolSpend[tool] = amount
}
}
// Payer configures the wallet/signing hook used to settle x402-paid tools.
// Without a payer, payment-required tool results are returned as clear errors.
func Payer(p x402.Payer) Option {
return func(o *Options) { o.Payer = p }
}
// Budget bounds autonomous x402 payments per Ask, in the asset's smallest
// unit (0 = unlimited). The budget is enforced by wrapper/x402.Client.
func Budget(amount int64) Option {
return func(o *Options) { o.Budget = amount }
}
// 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.
@@ -252,6 +295,12 @@ func ModelRetry(maxAttempts int, backoff time.Duration) Option {
}
}
// ModelRetryJitter adds bounded random jitter to provider retry backoff.
// Set 0 to disable.
func ModelRetryJitter(d time.Duration) Option {
return func(o *Options) { o.ModelRetryJitter = d }
}
// ToolRetry sets the tool retry budget and backoff for transient failures.
// Attempts include the first call. Retries are opt-in because tools may have
// side effects; keep handlers idempotent before enabling this.
+37 -3
View File
@@ -51,6 +51,8 @@ const (
AttrDispatch = "agent.dispatch"
AttrTrigger = "agent.trigger"
AttrRunEventKind = "agent.event.kind"
AttrSpend = "agent.spend"
AttrToolSpend = "agent.tool.spend"
)
type RunEvent struct {
@@ -73,6 +75,8 @@ type RunEvent struct {
Error string `json:"error,omitempty"`
ErrorKind string `json:"error_kind,omitempty"`
InputChars int `json:"input_chars,omitempty"`
Spent int64 `json:"spent,omitempty"`
ToolSpend int64 `json:"tool_spend,omitempty"`
}
type Usage = ai.Usage
@@ -82,7 +86,8 @@ type Usage = ai.Usage
type RunListOptions struct {
// Status, when set, keeps only runs with the matching status
// (for example "running", "done", "canceled", "timeout",
// "rate_limited", "error", or "refused").
// "rate_limited", "auth", "configuration", "unavailable",
// "provider_error", "error", or "refused").
Status string
// TraceID, when set, keeps only runs correlated with this trace id.
// A prefix is accepted so operators can paste the shortened trace id
@@ -110,6 +115,7 @@ type RunSummary struct {
LastKind string `json:"last_kind,omitempty"`
LastError string `json:"last_error,omitempty"`
LastErrorKind string `json:"last_error_kind,omitempty"`
Spent int64 `json:"spent,omitempty"`
}
func (a *agentImpl) tracer() trace.Tracer {
@@ -361,6 +367,7 @@ func (a *agentImpl) traceTool(next ai.ToolHandler) ai.ToolHandler {
return func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
info, _ := ai.RunInfoFrom(ctx)
start := time.Now()
spentBefore := a.spend
if a.opts.TraceProvider == nil {
res := next(ctx, call)
@@ -370,7 +377,7 @@ func (a *agentImpl) traceTool(next ai.ToolHandler) ai.ToolHandler {
if toolAttempts <= 0 {
toolAttempts = 1
}
a.recordRunEvent(RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "tool", Name: call.Name, Attempt: toolAttempts, MaxAttempts: a.opts.ToolMaxAttempts, LatencyMS: dur, Refused: res.Refused, Error: resErr, ErrorKind: classifyToolError(resErr)})
a.recordRunEvent(RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "tool", Name: call.Name, Attempt: toolAttempts, MaxAttempts: a.opts.ToolMaxAttempts, LatencyMS: dur, Refused: res.Refused, Error: resErr, ErrorKind: classifyToolError(resErr), Spent: a.spend, ToolSpend: a.spend - spentBefore})
return res
}
@@ -384,6 +391,7 @@ func (a *agentImpl) traceTool(next ai.ToolHandler) ai.ToolHandler {
ctx, span := a.tracer().Start(ctx, spanNameToolCall, trace.WithAttributes(spanAttrs...))
res := next(ctx, call)
dur := time.Since(start).Milliseconds()
toolSpend := a.spend - spentBefore
attrs := []attribute.KeyValue{attribute.Int64(AttrLatencyMS, dur)}
toolAttempts := res.Attempts
if toolAttempts <= 0 {
@@ -393,6 +401,9 @@ func (a *agentImpl) traceTool(next ai.ToolHandler) ai.ToolHandler {
if a.opts.ToolMaxAttempts > 0 {
attrs = append(attrs, attribute.Int(AttrToolMaxAttempts, a.opts.ToolMaxAttempts))
}
if toolSpend > 0 {
attrs = append(attrs, attribute.Int64(AttrSpend, a.spend), attribute.Int64(AttrToolSpend, toolSpend))
}
if res.Refused != "" {
attrs = append(attrs, attribute.Bool(AttrGuardrailBlock, true), attribute.String(AttrRefusal, res.Refused))
}
@@ -408,7 +419,7 @@ func (a *agentImpl) traceTool(next ai.ToolHandler) ai.ToolHandler {
} else {
span.SetStatus(codes.Ok, "")
}
a.recordSpanEvent(span, RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "tool", Name: call.Name, Attempt: toolAttempts, MaxAttempts: a.opts.ToolMaxAttempts, LatencyMS: dur, Refused: res.Refused, Error: resErr, ErrorKind: classifyToolError(resErr)})
a.recordSpanEvent(span, RunEvent{Time: time.Now(), RunID: info.RunID, ParentID: info.ParentID, Agent: info.Agent, Kind: "tool", Name: call.Name, Attempt: toolAttempts, MaxAttempts: a.opts.ToolMaxAttempts, LatencyMS: dur, Refused: res.Refused, Error: resErr, ErrorKind: classifyToolError(resErr), Spent: a.spend, ToolSpend: toolSpend})
span.End()
return res
}
@@ -495,6 +506,12 @@ func runEventAttributes(e RunEvent) []attribute.KeyValue {
if e.InputChars > 0 {
attrs = append(attrs, attribute.Int(AttrInputChars, e.InputChars))
}
if e.Spent > 0 {
attrs = append(attrs, attribute.Int64(AttrSpend, e.Spent))
}
if e.ToolSpend > 0 {
attrs = append(attrs, attribute.Int64(AttrToolSpend, e.ToolSpend))
}
attrs = appendUsage(attrs, e.Tokens)
if e.Refused != "" {
attrs = append(attrs, attribute.Bool(AttrGuardrailBlock, true), attribute.String(AttrRefusal, e.Refused))
@@ -529,6 +546,12 @@ func appendRunInfoAttributes(attrs []attribute.KeyValue, info ai.RunInfo) []attr
if info.Trigger != "" {
attrs = append(attrs, attribute.String(AttrTrigger, info.Trigger))
}
if info.Spent > 0 {
attrs = append(attrs, attribute.Int64(AttrSpend, info.Spent))
}
if info.ToolSpend > 0 {
attrs = append(attrs, attribute.Int64(AttrToolSpend, info.ToolSpend))
}
return attrs
}
@@ -615,6 +638,9 @@ func ListRunSummariesWithOptions(s store.Store, agentName string, opts RunListOp
if e.ErrorKind != "" {
summary.LastErrorKind = e.ErrorKind
}
if e.Spent > summary.Spent {
summary.Spent = e.Spent
}
}
if opts.Status != "" && summary.Status != opts.Status {
continue
@@ -662,6 +688,14 @@ func runErrorStatus(kind string) string {
return "timeout"
case ai.ErrorKindRateLimited:
return "rate_limited"
case ai.ErrorKindAuth:
return "auth"
case ai.ErrorKindConfiguration:
return "configuration"
case ai.ErrorKindUnavailable:
return "unavailable"
case ai.ErrorKindProvider:
return "provider_error"
default:
return "error"
}
+61 -1
View File
@@ -421,6 +421,63 @@ func spanAttributes(attrs []attribute.KeyValue) map[string]string {
return out
}
func TestAgentOpenTelemetryToolSpanIncludesSpend(t *testing.T) {
exp := tracetest.NewInMemoryExporter()
tp := trace.NewTracerProvider(trace.WithSyncer(exp))
st := store.NewMemoryStore()
a := New(Name("spender"), Provider("oteltest"), Model("unit-model"), WithStore(st), TraceProvider(tp), MaxSpend(10), ToolSpend("probe", 7), WithTool("probe", "probe", nil, func(ctx context.Context, input map[string]any) (string, error) {
info, ok := ai.RunInfoFrom(ctx)
if !ok {
t.Fatal("RunInfo missing from paid tool context")
}
if info.Spent != 7 || info.ToolSpend != 7 {
t.Fatalf("RunInfo spend = (%d, %d), want (7, 7)", info.Spent, info.ToolSpend)
}
return "ok", nil
}))
if _, err := a.Ask(context.Background(), "hello"); err != nil {
t.Fatal(err)
}
var sawToolSpan bool
for _, s := range exp.GetSpans().Snapshots() {
if s.Name() != spanNameToolCall {
continue
}
sawToolSpan = true
attrs := spanAttributes(s.Attributes())
if attrs[AttrSpend] != "7" || attrs[AttrToolSpend] != "7" {
t.Fatalf("tool span missing spend attributes: %#v", attrs)
}
if !spanEventHasAttribute(s.Events(), "agent.tool", AttrToolSpend, "7") {
t.Fatalf("tool event missing spend attribute: %#v", s.Events())
}
}
if !sawToolSpan {
t.Fatal("tool span not emitted")
}
summaries, err := ListRunSummaries(st, "spender")
if err != nil {
t.Fatal(err)
}
if len(summaries) != 1 || summaries[0].Spent != 7 {
t.Fatalf("summary spend = %#v, want 7", summaries)
}
}
func spanEventHasAttribute(events []trace.Event, name, key, value string) bool {
for _, e := range events {
if e.Name != name {
continue
}
attrs := spanAttributes(e.Attributes)
if attrs[key] == value {
return true
}
}
return false
}
func TestAgentOpenTelemetrySpansDelegateLineage(t *testing.T) {
exp := tracetest.NewInMemoryExporter()
tp := trace.NewTracerProvider(trace.WithSyncer(exp))
@@ -663,7 +720,10 @@ func TestRunStatusClassifiesOperationalErrorKinds(t *testing.T) {
{name: "canceled", kind: ai.ErrorKindCanceled, want: "canceled"},
{name: "timeout", kind: ai.ErrorKindTimeout, want: "timeout"},
{name: "rate limited", kind: ai.ErrorKindRateLimited, want: "rate_limited"},
{name: "provider", kind: ai.ErrorKindProvider, want: "error"},
{name: "auth", kind: ai.ErrorKindAuth, want: "auth"},
{name: "configuration", kind: ai.ErrorKindConfiguration, want: "configuration"},
{name: "unavailable", kind: ai.ErrorKindUnavailable, want: "unavailable"},
{name: "provider", kind: ai.ErrorKindProvider, want: "provider_error"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
+72
View File
@@ -29,6 +29,7 @@ var _ server.Option
type AgentService interface {
Chat(ctx context.Context, in *ChatRequest, opts ...client.CallOption) (*ChatResponse, error)
StreamChat(ctx context.Context, in *ChatRequest, opts ...client.CallOption) (Agent_StreamChatService, error)
}
type agentService struct {
@@ -53,6 +54,40 @@ func (c *agentService) Chat(ctx context.Context, in *ChatRequest, opts ...client
return out, nil
}
func (c *agentService) StreamChat(ctx context.Context, in *ChatRequest, opts ...client.CallOption) (Agent_StreamChatService, error) {
req := c.c.NewRequest(c.name, "Agent.StreamChat", in)
stream, err := c.c.Stream(ctx, req, opts...)
if err != nil {
return nil, err
}
if err := stream.Send(in); err != nil {
_ = stream.Close()
return nil, err
}
return &agentServiceStreamChat{stream}, nil
}
type Agent_StreamChatService interface {
Close() error
Recv() (*ChatResponse, error)
}
type agentServiceStreamChat struct {
stream client.Stream
}
func (x *agentServiceStreamChat) Close() error {
return x.stream.Close()
}
func (x *agentServiceStreamChat) Recv() (*ChatResponse, error) {
m := new(ChatResponse)
if err := x.stream.Recv(m); err != nil {
return nil, err
}
return m, nil
}
// Server API for Agent service
type AgentHandler interface {
@@ -62,6 +97,7 @@ type AgentHandler interface {
func RegisterAgentHandler(s server.Server, hdlr AgentHandler, opts ...server.HandlerOption) error {
type agent interface {
Chat(ctx context.Context, in *ChatRequest, out *ChatResponse) error
StreamChat(ctx context.Context, stream server.Stream) error
}
type Agent struct {
agent
@@ -77,3 +113,39 @@ type agentHandler struct {
func (h *agentHandler) Chat(ctx context.Context, in *ChatRequest, out *ChatResponse) error {
return h.AgentHandler.Chat(ctx, in, out)
}
func (h *agentHandler) StreamChat(ctx context.Context, stream server.Stream) error {
streamer, ok := h.AgentHandler.(interface {
StreamChat(context.Context, Agent_StreamChatStream) error
})
if !ok {
return fmt.Errorf("agent: StreamChat unsupported")
}
return streamer.StreamChat(ctx, &agentStreamChatStream{stream})
}
type Agent_StreamChatStream interface {
Close() error
Send(*ChatResponse) error
Recv() (*ChatRequest, error)
}
type agentStreamChatStream struct {
stream server.Stream
}
func (x *agentStreamChatStream) Close() error {
return x.stream.Close()
}
func (x *agentStreamChatStream) Send(m *ChatResponse) error {
return x.stream.Send(m)
}
func (x *agentStreamChatStream) Recv() (*ChatRequest, error) {
m := new(ChatRequest)
if err := x.stream.Recv(m); err != nil {
return nil, err
}
return m, nil
}
+1
View File
@@ -7,6 +7,7 @@ option go_package = "./proto;agent";
// Agent is the RPC interface for an AI agent.
service Agent {
rpc Chat(ChatRequest) returns (ChatResponse) {}
rpc StreamChat(ChatRequest) returns (stream ChatResponse) {}
}
message ChatRequest {
+32
View File
@@ -118,8 +118,14 @@ func TestStreamAskHelperRejectsUnsupportedAgent(t *testing.T) {
func TestAgentStreamUsesProviderStreamingAndRecordsAssistantMemory(t *testing.T) {
var sawRequest bool
var sawRunInfo bool
fakeStream = func(ctx context.Context, opts ai.Options, req *ai.Request) (ai.Stream, error) {
sawRequest = true
info, ok := ai.RunInfoFrom(ctx)
if !ok || info.RunID == "" || info.Agent != "provider-stream" {
t.Fatalf("RunInfo = %#v, %v; want provider stream run metadata", info, ok)
}
sawRunInfo = true
if req.Prompt != "stream the answer" {
t.Fatalf("Prompt = %q, want stream the answer", req.Prompt)
}
@@ -153,6 +159,9 @@ func TestAgentStreamUsesProviderStreamingAndRecordsAssistantMemory(t *testing.T)
if !sawRequest {
t.Fatal("provider Stream was not called")
}
if !sawRunInfo {
t.Fatal("provider Stream did not receive RunInfo")
}
if reply != "hello" {
t.Fatalf("reply = %q, want hello", reply)
}
@@ -162,6 +171,29 @@ func TestAgentStreamUsesProviderStreamingAndRecordsAssistantMemory(t *testing.T)
}
}
func TestAgentStreamCanceledContextSkipsProviderCallAndMemory(t *testing.T) {
calls := 0
fakeStream = func(ctx context.Context, opts ai.Options, req *ai.Request) (ai.Stream, error) {
calls++
return &sliceStream{chunks: []string{"late"}}, nil
}
defer func() { fakeStream = nil }()
ctx, cancel := context.WithCancel(context.Background())
cancel()
a := newTestAgent(Name("provider-stream-cancel"))
_, err := a.Stream(ctx, "do not start")
if !errors.Is(err, context.Canceled) {
t.Fatalf("Stream error = %v, want context canceled", err)
}
if calls != 0 {
t.Fatalf("provider Stream calls = %d, want 0 after caller cancellation", calls)
}
if got := a.mem.Messages(); len(got) != 0 {
t.Fatalf("memory = %#v, want no recorded canceled stream turn", got)
}
}
func TestResumeStreamAskDoesNotReplayCompletedTool(t *testing.T) {
ctx := context.Background()
cp := flow.StoreCheckpoint(store.NewStore(), "stream-resume-agent")
+3
View File
@@ -228,6 +228,9 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
// it may contain a text-encoded tool call. The agent harness
// inspects Reply for text fallback calls after Generate returns.
resp.Reply = followUpResp.Reply
if len(toolResults) > 0 {
resp.Answer = strings.Join(toolResults, "\n")
}
} else {
resp.Answer = atlascloudAnswerWithRequiredToolMarkers(followUpResp.Reply, toolResults, allToolCalls)
}
+68 -8
View File
@@ -13,6 +13,27 @@ import (
"go-micro.dev/v6/ai"
)
type atlascloudRoundTripFunc func(*http.Request) (*http.Response, error)
func (fn atlascloudRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
func useAtlascloudJSONTransport(t *testing.T, handler func(*http.Request) string) {
t.Helper()
previous := http.DefaultTransport
http.DefaultTransport = atlascloudRoundTripFunc(func(req *http.Request) (*http.Response, error) {
body := handler(req)
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
})
t.Cleanup(func() { http.DefaultTransport = previous })
}
func TestProvider_String(t *testing.T) {
p := NewProvider()
if p.String() != "atlascloud" {
@@ -477,27 +498,26 @@ func TestProvider_GenerateExecutesMultiStepFollowUpToolCalls(t *testing.T) {
func TestProvider_GeneratePreservesFollowUpTextToolCallInReply(t *testing.T) {
var bodies []map[string]any
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
useAtlascloudJSONTransport(t, func(r *http.Request) string {
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode request: %v", err)
}
bodies = append(bodies, body)
w.Header().Set("Content-Type", "application/json")
switch len(bodies) {
case 1:
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"","tool_calls":[{"id":"call-1","function":{"name":"conformance_echo","arguments":"{\"value\":\"agent-conformance\"}"}}]}}]}`))
return `{"choices":[{"message":{"content":"","tool_calls":[{"id":"call-1","function":{"name":"conformance_echo","arguments":"{\"value\":\"agent-conformance\"}"}}]}}]}`
case 2:
_, _ = w.Write([]byte(`{"choices":[{"message":{"content":"<tool_call name=\"delegate\">{\"task\":\"summarize the conformance marker\",\"to\":\"blocked-reviewer\"}</tool_call>"}}]}`))
return `{"choices":[{"message":{"content":"<tool_call name=\"delegate\">{\"task\":\"summarize the conformance marker\",\"to\":\"blocked-reviewer\"}</tool_call>"}}]}`
default:
t.Fatalf("unexpected API call %d", len(bodies))
return ""
}
}))
defer ts.Close()
})
p := NewProvider(
ai.WithAPIKey("test-key"),
ai.WithBaseURL(ts.URL),
ai.WithBaseURL("https://atlascloud.test"),
ai.WithToolHandler(func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
if call.Name != "conformance_echo" {
t.Fatalf("unexpected structured tool call %+v", call)
@@ -518,8 +538,48 @@ func TestProvider_GeneratePreservesFollowUpTextToolCallInReply(t *testing.T) {
if !strings.Contains(resp.Reply, `<tool_call name="delegate">`) {
t.Fatalf("Reply = %q, want tagged delegate follow-up for agent text fallback", resp.Reply)
}
if !strings.Contains(resp.Answer, "agent-conformance-ok") {
t.Fatalf("Answer = %q, want structured tool result preserved separately", resp.Answer)
}
}
func TestProvider_GenerateFollowUpTextToolCallWithoutToolResultLeavesAnswerEmpty(t *testing.T) {
var calls int
useAtlascloudJSONTransport(t, func(r *http.Request) string {
calls++
switch calls {
case 1:
return `{"choices":[{"message":{"content":"","tool_calls":[{"id":"call-1","function":{"name":"conformance_echo","arguments":"{\"value\":\"agent-conformance\"}"}}]}}]}`
case 2:
return `{"choices":[{"message":{"content":"<tool_call name=\"delegate\">{\"task\":\"summarize\",\"to\":\"blocked-reviewer\"}</tool_call>"}}]}`
default:
t.Fatalf("unexpected API call %d", calls)
return ""
}
})
p := NewProvider(
ai.WithAPIKey("test-key"),
ai.WithBaseURL("https://atlascloud.test"),
ai.WithToolHandler(func(ctx context.Context, call ai.ToolCall) ai.ToolResult {
return ai.ToolResult{ID: call.ID}
}),
)
resp, err := p.Generate(context.Background(), &ai.Request{
Prompt: "run conformance",
Tools: []ai.Tool{
{Name: "conformance_echo", Description: "echo conformance marker", Properties: map[string]any{"value": map[string]any{"type": "string"}}},
{Name: "delegate", Description: "delegate work", Properties: map[string]any{"task": map[string]any{"type": "string"}, "to": map[string]any{"type": "string"}}},
},
})
if err != nil {
t.Fatalf("Generate returned error: %v", err)
}
if !strings.Contains(resp.Reply, `<tool_call name="delegate">`) {
t.Fatalf("Reply = %q, want tagged delegate follow-up", resp.Reply)
}
if resp.Answer != "" {
t.Fatalf("Answer = %q, want follow-up text preserved only as Reply", resp.Answer)
t.Fatalf("Answer = %q, want no invented answer without structured tool content", resp.Answer)
}
}
+3 -3
View File
@@ -35,7 +35,7 @@ func TestRegisteredProviders(t *testing.T) {
}
got = ai.RegisteredProviders("stream")
want = []string{"anthropic", "atlascloud", "groq", "minimax", "mistral", "openai", "together"}
want = []string{"anthropic", "atlascloud", "gemini", "groq", "minimax", "mistral", "openai", "together"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("RegisteredProviders(stream) = %#v, want %#v", got, want)
}
@@ -46,7 +46,7 @@ func TestCapabilityRows(t *testing.T) {
want := []ai.CapabilityRow{
{Provider: "anthropic", Capabilities: ai.Capabilities{Model: true, Stream: true, ToolStream: true}},
{Provider: "atlascloud", Capabilities: ai.Capabilities{Model: true, Image: true, Video: true, Stream: true}},
{Provider: "gemini", Capabilities: ai.Capabilities{Model: true}},
{Provider: "gemini", Capabilities: ai.Capabilities{Model: true, Stream: true}},
{Provider: "groq", Capabilities: ai.Capabilities{Model: true, Stream: true, ToolStream: true}},
{Provider: "minimax", Capabilities: ai.Capabilities{Model: true, Stream: true, ToolStream: true}},
{Provider: "mistral", Capabilities: ai.Capabilities{Model: true, Stream: true, ToolStream: true}},
@@ -90,7 +90,7 @@ func TestRegisterStream(t *testing.T) {
}
got := ai.RegisteredProviders("stream")
want := []string{"anthropic", "atlascloud", "groq", "minimax", "mistral", "openai", "test-stream", "together"}
want := []string{"anthropic", "atlascloud", "gemini", "groq", "minimax", "mistral", "openai", "test-stream", "together"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("RegisteredProviders(stream) = %#v, want %#v", got, want)
}
+136 -4
View File
@@ -10,6 +10,7 @@
package gemini
import (
"bufio"
"bytes"
"context"
"encoding/json"
@@ -25,6 +26,7 @@ func init() {
ai.Register("gemini", func(opts ...ai.Option) ai.Model {
return NewProvider(opts...)
})
ai.RegisterStream("gemini")
}
// Provider implements the ai.Model interface for Google Gemini.
@@ -69,9 +71,7 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
})
}
contents := []map[string]any{
{"role": "user", "parts": []map[string]any{{"text": req.Prompt}}},
}
contents := geminiContents(req)
apiReq := map[string]any{
"contents": contents,
@@ -135,7 +135,121 @@ func (p *Provider) Generate(ctx context.Context, req *ai.Request, opts ...ai.Gen
}
func (p *Provider) Stream(ctx context.Context, req *ai.Request, opts ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("%w: gemini provider", ai.ErrStreamingUnsupported)
apiReq := map[string]any{
"contents": geminiContents(req),
}
if req.SystemPrompt != "" {
apiReq["system_instruction"] = map[string]any{
"parts": []map[string]any{{"text": req.SystemPrompt}},
}
}
if p.opts.MaxTokens > 0 {
apiReq["generationConfig"] = map[string]any{"maxOutputTokens": p.opts.MaxTokens}
}
reqBody, err := json.Marshal(apiReq)
if err != nil {
return nil, fmt.Errorf("failed to marshal stream request: %w", err)
}
apiURL := strings.TrimRight(p.opts.BaseURL, "/") +
"/v1beta/models/" + p.opts.Model + ":streamGenerateContent?alt=sse"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(reqBody))
if err != nil {
return nil, fmt.Errorf("failed to create stream request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "text/event-stream")
httpReq.Header.Set("x-goog-api-key", p.opts.APIKey)
httpResp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("stream API request failed: %w", err)
}
if httpResp.StatusCode != http.StatusOK {
defer httpResp.Body.Close()
respBody, _ := io.ReadAll(httpResp.Body)
return nil, ai.NewHTTPError(httpResp, respBody)
}
return &streamReader{body: httpResp.Body, scanner: bufio.NewScanner(httpResp.Body)}, nil
}
type streamReader struct {
body io.ReadCloser
scanner *bufio.Scanner
closed bool
}
func (s *streamReader) Recv() (*ai.Response, error) {
for s.scanner.Scan() {
line := strings.TrimSpace(s.scanner.Text())
if line == "" || strings.HasPrefix(line, ":") || strings.HasPrefix(line, "event:") {
continue
}
if !strings.HasPrefix(line, "data:") {
continue
}
data := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if data == "[DONE]" {
return nil, io.EOF
}
var chunk struct {
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
Status string `json:"status"`
} `json:"error"`
Candidates []struct {
Content struct {
Parts []struct {
Text string `json:"text"`
} `json:"parts"`
} `json:"content"`
} `json:"candidates"`
UsageMetadata *struct {
PromptTokenCount int `json:"promptTokenCount"`
CandidatesTokenCount int `json:"candidatesTokenCount"`
TotalTokenCount int `json:"totalTokenCount"`
} `json:"usageMetadata"`
}
if err := json.Unmarshal([]byte(data), &chunk); err != nil {
return nil, fmt.Errorf("failed to parse stream chunk: %w", err)
}
if chunk.Error != nil {
return nil, fmt.Errorf("gemini stream error (%s): %s", chunk.Error.Status, chunk.Error.Message)
}
for _, candidate := range chunk.Candidates {
var parts []string
for _, part := range candidate.Content.Parts {
if part.Text != "" {
parts = append(parts, part.Text)
}
}
if len(parts) > 0 {
return &ai.Response{Reply: strings.Join(parts, "")}, nil
}
}
if chunk.UsageMetadata != nil {
return &ai.Response{Usage: ai.Usage{
InputTokens: chunk.UsageMetadata.PromptTokenCount,
OutputTokens: chunk.UsageMetadata.CandidatesTokenCount,
TotalTokens: chunk.UsageMetadata.TotalTokenCount,
}}, nil
}
}
if err := s.scanner.Err(); err != nil {
return nil, err
}
return nil, io.EOF
}
func (s *streamReader) Close() error {
if s.closed {
return nil
}
s.closed = true
return s.body.Close()
}
func (p *Provider) callAPI(ctx context.Context, req map[string]any) (*ai.Response, []map[string]any, error) {
@@ -224,3 +338,21 @@ type functionCallPB struct {
Name string `json:"name"`
Args map[string]any `json:"args"`
}
func geminiContents(req *ai.Request) []map[string]any {
contents := make([]map[string]any, 0, len(req.Messages)+1)
for _, m := range req.Messages {
role := m.Role
if role == "assistant" {
role = "model"
}
if role == "system" || role == "" {
continue
}
contents = append(contents, map[string]any{"role": role, "parts": []map[string]any{{"text": fmt.Sprint(m.Content)}}})
}
if req.Prompt != "" {
contents = append(contents, map[string]any{"role": "user", "parts": []map[string]any{{"text": req.Prompt}}})
}
return contents
}
+103 -6
View File
@@ -2,7 +2,12 @@ package gemini
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go-micro.dev/v6/ai"
@@ -81,16 +86,108 @@ func TestProvider_Generate_NoAPIKey(t *testing.T) {
}
}
func TestProvider_Stream_NotImplemented(t *testing.T) {
p := NewProvider()
func TestProvider_Stream(t *testing.T) {
var sawRequest bool
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sawRequest = true
if r.URL.Path != "/v1beta/models/gemini-2.5-flash:streamGenerateContent" {
t.Fatalf("path = %s, want streamGenerateContent", r.URL.Path)
}
if r.URL.Query().Get("alt") != "sse" {
t.Fatalf("alt = %q, want sse", r.URL.Query().Get("alt"))
}
if got := r.Header.Get("Accept"); got != "text/event-stream" {
t.Fatalf("Accept = %q, want text/event-stream", got)
}
if got := r.Header.Get("x-goog-api-key"); got != "test-key" {
t.Fatalf("x-goog-api-key = %q, want test-key", got)
}
req := &ai.Request{
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatalf("decode request: %v", err)
}
contents, ok := body["contents"].([]any)
if !ok || len(contents) != 3 {
t.Fatalf("contents = %#v, want history + prompt", body["contents"])
}
second := contents[1].(map[string]any)
if second["role"] != "model" {
t.Fatalf("assistant history role = %#v, want model", second["role"])
}
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hel\"}]}}]}\n\n"))
_, _ = w.Write([]byte("data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"lo\"}]}}],\"usageMetadata\":{\"promptTokenCount\":3,\"candidatesTokenCount\":2,\"totalTokenCount\":5}}\n\n"))
_, _ = w.Write([]byte("data: [DONE]\n\n"))
}))
defer ts.Close()
p := NewProvider(ai.WithAPIKey("test-key"), ai.WithBaseURL(ts.URL))
stream, err := p.Stream(context.Background(), &ai.Request{
Messages: []ai.Message{
{Role: "user", Content: "previous question"},
{Role: "assistant", Content: "previous answer"},
},
Prompt: "Hello",
})
if err != nil {
t.Fatalf("Stream returned error: %v", err)
}
defer stream.Close()
if !sawRequest {
t.Fatal("server did not receive stream request")
}
_, err := p.Stream(context.Background(), req)
if !errors.Is(err, ai.ErrStreamingUnsupported) {
t.Fatalf("Stream error = %v, want ErrStreamingUnsupported", err)
first, err := stream.Recv()
if err != nil || first.Reply != "hel" {
t.Fatalf("first chunk = %#v, %v; want hel", first, err)
}
second, err := stream.Recv()
if err != nil || second.Reply != "lo" {
t.Fatalf("second chunk = %#v, %v; want lo", second, err)
}
if _, err := stream.Recv(); !errors.Is(err, io.EOF) {
t.Fatalf("final error = %v, want EOF", err)
}
}
func TestProvider_StreamPropagatesMalformedChunk(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: {bad json}\n\n"))
}))
defer ts.Close()
p := NewProvider(ai.WithAPIKey("test-key"), ai.WithBaseURL(ts.URL))
stream, err := p.Stream(context.Background(), &ai.Request{Prompt: "Hello"})
if err != nil {
t.Fatalf("Stream returned error: %v", err)
}
defer stream.Close()
if _, err := stream.Recv(); err == nil {
t.Fatal("Recv returned nil error for malformed chunk")
}
}
func TestProvider_StreamPropagatesProviderError(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "quota exhausted", http.StatusTooManyRequests)
}))
defer ts.Close()
p := NewProvider(ai.WithAPIKey("test-key"), ai.WithBaseURL(ts.URL))
stream, err := p.Stream(context.Background(), &ai.Request{Prompt: "Hello"})
if err == nil {
_ = stream.Close()
t.Fatal("Stream returned nil error for provider failure")
}
if !strings.Contains(err.Error(), "429") || !strings.Contains(err.Error(), "quota exhausted") {
t.Fatalf("Stream error = %v, want provider status and body", err)
}
if strings.Contains(err.Error(), "test-key") {
t.Fatal("stream error leaked API key")
}
}
+5
View File
@@ -109,6 +109,9 @@ const (
RefusedMaxSteps = "max_steps"
RefusedLoop = "loop"
RefusedApproval = "approval"
// RefusedSpendBudget means an agent refused a paid tool before execution
// because the configured per-run x402 spend budget would be exceeded.
RefusedSpendBudget = "spend_budget"
)
// RunInfo describes the agent run a tool call belongs to. The agent
@@ -132,6 +135,8 @@ type RunInfo struct {
VerificationFeedback string // feedback from the previous failed verifier attempt, when retrying a flow step
Dispatch string // how the run was dispatched (direct, broker, schedule, resume) when known
Trigger string // external trigger or schedule label that started the run, when known
Spent int64 // cumulative paid x402 spend in this run, in the asset's smallest unit
ToolSpend int64 // paid x402 spend attributed to the current tool call, in the asset's smallest unit
}
type runInfoKey struct{}
+28 -7
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"math/rand/v2"
"net/http"
"strconv"
"strings"
@@ -84,12 +85,14 @@ func parseRetryAfter(value string, now time.Time) time.Duration {
type ErrorKind string
const (
ErrorKindUnknown ErrorKind = "unknown"
ErrorKindCanceled ErrorKind = "canceled"
ErrorKindTimeout ErrorKind = "timeout"
ErrorKindRateLimited ErrorKind = "rate_limited"
ErrorKindUnavailable ErrorKind = "unavailable"
ErrorKindProvider ErrorKind = "provider"
ErrorKindUnknown ErrorKind = "unknown"
ErrorKindCanceled ErrorKind = "canceled"
ErrorKindTimeout ErrorKind = "timeout"
ErrorKindRateLimited ErrorKind = "rate_limited"
ErrorKindUnavailable ErrorKind = "unavailable"
ErrorKindAuth ErrorKind = "auth"
ErrorKindConfiguration ErrorKind = "configuration"
ErrorKindProvider ErrorKind = "provider"
)
// ClassifiedError is implemented by errors that expose a stable ErrorKind.
@@ -130,6 +133,9 @@ type GeneratePolicy struct {
Timeout time.Duration
MaxAttempts int
Backoff time.Duration
// Jitter adds up to this duration of random delay to retry backoff.
// It is opt-in so existing retry timing remains deterministic by default.
Jitter time.Duration
}
// GenerateWithRetry calls m.Generate with per-attempt timeout and bounded retry.
@@ -183,7 +189,7 @@ func GenerateWithRetry(ctx context.Context, m Model, req *Request, policy Genera
// 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 := retryBackoff(err, attempt, policy.Backoff)
backoff := retryBackoffWithJitter(err, attempt, policy.Backoff, policy.Jitter)
t := time.NewTimer(backoff)
select {
case <-ctx.Done():
@@ -219,6 +225,10 @@ func generateAttempt(ctx context.Context, m Model, req *Request, opts ...Generat
}
func retryBackoff(err error, attempt int, base time.Duration) time.Duration {
return retryBackoffWithJitter(err, attempt, base, 0)
}
func retryBackoffWithJitter(err error, attempt int, base, jitter time.Duration) time.Duration {
backoff := base
if backoff <= 0 {
backoff = 200 * time.Millisecond
@@ -236,6 +246,9 @@ func retryBackoff(err error, attempt int, base time.Duration) time.Duration {
backoff = delay
}
}
if jitter > 0 {
backoff += time.Duration(rand.Int64N(int64(jitter) + 1))
}
if backoff > 30*time.Second {
return 30 * time.Second
}
@@ -265,6 +278,10 @@ func ClassifyError(err error) ErrorKind {
switch {
case code == 429:
return ErrorKindRateLimited
case code == 401 || code == 403:
return ErrorKindAuth
case code == 400 || code == 404:
return ErrorKindConfiguration
case code >= 500:
return ErrorKindUnavailable
case code > 0:
@@ -277,6 +294,10 @@ func ClassifyError(err error) ErrorKind {
return ErrorKindRateLimited
case strings.Contains(msg, "timeout") || strings.Contains(msg, "deadline"):
return ErrorKindTimeout
case strings.Contains(msg, "unauthorized") || strings.Contains(msg, "forbidden") || strings.Contains(msg, "invalid api key") || strings.Contains(msg, "api key") || strings.Contains(msg, "credential"):
return ErrorKindAuth
case strings.Contains(msg, "missing") || strings.Contains(msg, "not configured") || strings.Contains(msg, "configuration") || strings.Contains(msg, "unsupported model") || strings.Contains(msg, "model not found"):
return ErrorKindConfiguration
case strings.Contains(msg, "temporar") || strings.Contains(msg, "unavailable"):
return ErrorKindUnavailable
default:
+17 -1
View File
@@ -230,9 +230,13 @@ func TestClassifyErrorDistinguishesOperationalOutcomes(t *testing.T) {
{name: "canceled", err: context.Canceled, want: ErrorKindCanceled},
{name: "timeout", err: context.DeadlineExceeded, want: ErrorKindTimeout},
{name: "rate limit status", err: statusErr(429), want: ErrorKindRateLimited},
{name: "auth status", err: statusErr(401), want: ErrorKindAuth},
{name: "configuration status", err: statusErr(400), want: ErrorKindConfiguration},
{name: "unavailable status", err: statusErr(503), want: ErrorKindUnavailable},
{name: "provider status", err: statusErr(400), want: ErrorKindProvider},
{name: "provider status", err: statusErr(409), want: ErrorKindProvider},
{name: "rate limit text", err: errors.New("rate limit exceeded"), want: ErrorKindRateLimited},
{name: "auth text", err: errors.New("invalid API key"), want: ErrorKindAuth},
{name: "configuration text", err: errors.New("model not found"), want: ErrorKindConfiguration},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -423,3 +427,15 @@ func TestHTTPErrorExposesStatusAndRetryAfter(t *testing.T) {
t.Fatalf("RetryAfter() = %s, want 2s", got)
}
}
func TestRetryBackoffAddsBoundedJitter(t *testing.T) {
const base = 10 * time.Millisecond
const jitter = 5 * time.Millisecond
for range 100 {
got := retryBackoffWithJitter(errors.New("temporary"), 1, base, jitter)
if got < base || got > base+jitter {
t.Fatalf("retryBackoffWithJitter() = %s, want in [%s, %s]", got, base, base+jitter)
}
}
}
+1 -18
View File
@@ -216,6 +216,7 @@ func TestConfiguredProviderStreamsSkipWithoutCredentials(t *testing.T) {
{provider: "together", keyEnv: "TOGETHER_API_KEY", modelEnv: "TOGETHER_MODEL"},
{provider: "atlascloud", keyEnv: "ATLASCLOUD_API_KEY", modelEnv: "ATLASCLOUD_MODEL"},
{provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY", modelEnv: "ANTHROPIC_MODEL"},
{provider: "gemini", keyEnv: "GEMINI_API_KEY", modelEnv: "GEMINI_MODEL"},
} {
tc := tc
t.Run(tc.provider, func(t *testing.T) {
@@ -256,24 +257,6 @@ func TestConfiguredProviderStreamsSkipWithoutCredentials(t *testing.T) {
}
}
func TestUnsupportedProvidersReturnStreamingUnsupportedAndStayUnregistered(t *testing.T) {
for _, provider := range []string{"gemini"} {
provider := provider
t.Run(provider, func(t *testing.T) {
if caps := ai.ProviderCapabilities(provider); caps.Stream {
t.Fatalf("ProviderCapabilities(%q).Stream = true, want false", provider)
}
_, err := ai.New(provider, ai.WithAPIKey("test-key")).Stream(context.Background(), &ai.Request{Prompt: "Hello"})
if !errors.Is(err, ai.ErrStreamingUnsupported) {
t.Fatalf("Stream error = %v, want ErrStreamingUnsupported", err)
}
if err != nil && strings.Contains(err.Error(), "test-key") {
t.Fatal("streaming unsupported error leaked API key")
}
})
}
}
func conformingStreamProviders(t *testing.T) []string {
t.Helper()
providers := ai.RegisteredProviders("stream")
+1 -1
View File
@@ -3,7 +3,7 @@ package redis
import (
"context"
rclient "github.com/go-redis/redis/v8"
rclient "github.com/redis/go-redis/v9"
"go-micro.dev/v6/cache"
)
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"reflect"
"testing"
rclient "github.com/go-redis/redis/v8"
rclient "github.com/redis/go-redis/v9"
"go-micro.dev/v6/cache"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"time"
rclient "github.com/go-redis/redis/v8"
rclient "github.com/redis/go-redis/v9"
"go-micro.dev/v6/cache"
)
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# check-versions.sh — Run `go list -m -versions` for every phantom module path
# declared in retract-phantom.sh.
#
# Usage: ./check-versions.sh [--dry-run]
#
# --dry-run print the paths only, without running go list
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE="$SCRIPT_DIR/retract-phantom.sh"
DRY_RUN=false
for arg in "$@"; do
case "$arg" in
--dry-run) DRY_RUN=true ;;
esac
done
if [[ ! -f "$SOURCE" ]]; then
echo "error: $SOURCE not found" >&2
exit 1
fi
mapfile -t PATHS < <(
awk '
/^PHANTOM_PATHS=\(/ { in_arr = 1; next }
in_arr && /^\)/ { exit }
in_arr {
gsub(/^[[:space:]]+|[[:space:]]+$/, "")
if ($0 != "" && $0 !~ /^#/) print
}
' "$SOURCE"
)
if [[ ${#PATHS[@]} -eq 0 ]]; then
echo "error: no phantom paths parsed from $SOURCE" >&2
exit 1
fi
echo "checking ${#PATHS[@]} phantom module paths"
for path in "${PATHS[@]}"; do
if $DRY_RUN; then
echo "$path"
continue
fi
printf '%-70s ' "$path"
go list -m -versions "$path" 2>/dev/null || printf '(no versions found)'
echo
done
+60
View File
@@ -0,0 +1,60 @@
package client
import (
"context"
raw "go-micro.dev/v6/codec/bytes"
"go-micro.dev/v6/internal/network"
"go-micro.dev/v6/metadata"
"go-micro.dev/v6/transport"
"go-micro.dev/v6/transport/headers"
)
// localCall is the in-process fast-path for Call. When Local is enabled
// and the callee runs in this same process, a unary request whose body and
// response are raw frames (codec/bytes.Frame) is dispatched straight to the
// server's handlers via internal/network — no dial, no codec-over-socket,
// no transport pump. It returns handled=false to fall back to the network path
// for anything it does not cover (disabled, streaming, non-frame bodies, or a
// service not registered in-process), so behavior is unchanged unless the
// fast-path fully applies.
func (r *rpcClient) localCall(ctx context.Context, req Request, resp interface{}) (handled bool, err error) {
if !r.opts.Local || req.Stream() {
return false, nil
}
reqFrame, ok := req.Body().(*raw.Frame)
if !ok {
return false, nil
}
respFrame, ok := resp.(*raw.Frame)
if !ok {
return false, nil
}
dispatch, ok := network.Lookup(req.Service())
if !ok {
return false, nil
}
header := make(map[string]string)
if md, ok := metadata.FromContext(ctx); ok {
for k, v := range md {
if k == headers.Message { // pub/sub topic header, never forwarded
continue
}
header[k] = v
}
}
header[headers.Request] = req.Service()
header[headers.Endpoint] = req.Endpoint()
header["Content-Type"] = req.ContentType()
header["Accept"] = req.ContentType()
reply, err := dispatch(ctx, &transport.Message{Header: header, Body: reqFrame.Data})
if err != nil {
return true, err
}
if reply != nil {
respFrame.Data = reply.Body
}
return true, nil
}
+139
View File
@@ -0,0 +1,139 @@
package client_test
import (
"context"
"encoding/json"
"testing"
"time"
"go-micro.dev/v6/client"
raw "go-micro.dev/v6/codec/bytes"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/selector"
"go-micro.dev/v6/server"
)
type EchoReq struct {
Msg string `json:"msg"`
}
type EchoRsp struct {
Msg string `json:"msg"`
}
type EchoHandler struct{}
func (EchoHandler) Echo(_ context.Context, req *EchoReq, rsp *EchoRsp) error {
rsp.Msg = "echo:" + req.Msg
return nil
}
// startEchoServer starts a real server on the given registry and returns a stop
// func. The server is reachable over the network transport and (via Start)
// registered for the in-process fast-path.
func startEchoServer(t testing.TB, reg registry.Registry) func() {
t.Helper()
srv := server.NewServer(
server.Name("echo.local"),
server.Address("127.0.0.1:0"),
server.Registry(reg),
)
if err := srv.Handle(srv.NewHandler(&EchoHandler{})); err != nil {
t.Fatalf("handle: %v", err)
}
if err := srv.Start(); err != nil {
t.Fatalf("start: %v", err)
}
// Wait for registration so the client's selector can find a node.
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if svcs, err := reg.GetService("echo.local"); err == nil && len(svcs) > 0 && len(svcs[0].Nodes) > 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
return func() { _ = srv.Stop() }
}
func newEchoClient(reg registry.Registry, opts ...client.Option) client.Client {
base := []client.Option{
client.Registry(reg),
client.Selector(selector.NewSelector(selector.Registry(reg))),
client.ContentType("application/json"),
}
return client.NewClient(append(base, opts...)...)
}
// callEcho makes an echo call with a raw-frame body (the shape agent/MCP/flow
// dispatch uses) and returns the decoded reply.
func callEcho(t testing.TB, cl client.Client, msg string) EchoRsp {
t.Helper()
body, _ := json.Marshal(EchoReq{Msg: msg})
req := cl.NewRequest("echo.local", "EchoHandler.Echo", &raw.Frame{Data: body}, client.WithContentType("application/json"))
var rsp raw.Frame
if err := cl.Call(context.Background(), req, &rsp); err != nil {
t.Fatalf("call: %v", err)
}
var out EchoRsp
if err := json.Unmarshal(rsp.Data, &out); err != nil {
t.Fatalf("decode reply %q: %v", rsp.Data, err)
}
return out
}
// TestLocalMatchesNetwork proves the in-process fast-path returns the
// exact same result as the network path for the same handler and request.
func TestLocalMatchesNetwork(t *testing.T) {
reg := registry.NewMemoryRegistry()
stop := startEchoServer(t, reg)
defer stop()
net := newEchoClient(reg) // network path
local := newEchoClient(reg, client.Local()) // in-process fast-path
netRsp := callEcho(t, net, "hi")
localRsp := callEcho(t, local, "hi")
if netRsp.Msg != "echo:hi" {
t.Fatalf("network reply = %q, want echo:hi", netRsp.Msg)
}
if localRsp != netRsp {
t.Fatalf("fast-path reply %+v != network reply %+v", localRsp, netRsp)
}
}
// TestLocalFallsBackWhenNotLocal confirms a service not registered
// in-process still works via the network path even with Local on.
func TestLocalFallsBackWhenNotLocal(t *testing.T) {
reg := registry.NewMemoryRegistry()
stop := startEchoServer(t, reg)
defer stop()
// Local is on, but the call still resolves — the fast-path only
// engages when it fully applies, otherwise the network path runs.
local := newEchoClient(reg, client.Local())
if got := callEcho(t, local, "x").Msg; got != "echo:x" {
t.Fatalf("reply = %q, want echo:x", got)
}
}
func benchmarkEcho(b *testing.B, opts ...client.Option) {
reg := registry.NewMemoryRegistry()
stop := startEchoServer(b, reg)
defer stop()
cl := newEchoClient(reg, opts...)
body, _ := json.Marshal(EchoReq{Msg: "hi"})
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
req := cl.NewRequest("echo.local", "EchoHandler.Echo", &raw.Frame{Data: body}, client.WithContentType("application/json"))
var rsp raw.Frame
if err := cl.Call(context.Background(), req, &rsp); err != nil {
b.Fatalf("call: %v", err)
}
}
}
func BenchmarkNetworkCall(b *testing.B) { benchmarkEcho(b) }
func BenchmarkLocalCall(b *testing.B) { benchmarkEcho(b, client.Local()) }
+16
View File
@@ -68,6 +68,11 @@ type Options struct {
PoolSize int
PoolTTL time.Duration
PoolCloseTimeout time.Duration
// Local, when true, lets a unary Call to a service running in this
// same process skip the network transport and dispatch directly to that
// server's handlers (raw byte bodies only). Off by default.
Local bool
}
// CallOptions are options used to make calls to a server.
@@ -181,6 +186,17 @@ func ContentType(ct string) Option {
}
}
// Local enables the in-process fast-path: a unary Call to a service
// running in the same process dispatches straight to that server's handlers
// (skipping dial, codec-over-socket, and the transport pump) when both request
// and response bodies are raw frames (codec/bytes.Frame) — the shape agent,
// MCP, and flow tool calls use. Falls back to the network path otherwise.
func Local() Option {
return func(o *Options) {
o.Local = true
}
}
// PoolSize sets the connection pool size.
func PoolSize(d int) Option {
return func(o *Options) {
+6
View File
@@ -83,6 +83,12 @@ func (r *rpcClient) call(
resp interface{},
opts CallOptions,
) error {
// In-process fast-path: if the callee runs in this process and both bodies
// are raw frames, dispatch directly and skip the network entirely.
if handled, err := r.localCall(ctx, req, resp); handled {
return err
}
address := node.Address
logger := r.Options().Logger
-19
View File
@@ -1,19 +0,0 @@
FROM golang:1.23-alpine AS builder
RUN apk add --no-cache git
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /micro-mcp-gateway ./cmd/micro-mcp-gateway
FROM alpine:3.20
RUN apk add --no-cache ca-certificates
COPY --from=builder /micro-mcp-gateway /usr/local/bin/micro-mcp-gateway
EXPOSE 3000
ENTRYPOINT ["micro-mcp-gateway"]
CMD ["--address", ":3000"]
-286
View File
@@ -1,286 +0,0 @@
// Command micro-mcp-gateway runs a standalone MCP gateway that discovers
// go-micro services via a registry and exposes them as AI-accessible tools
// through the Model Context Protocol.
//
// This is the production deployment binary for the MCP gateway, intended
// to run independently of your services.
//
// Usage:
//
// # mDNS (development default)
// micro-mcp-gateway --address :3000
//
// # Consul
// micro-mcp-gateway --address :3000 --registry consul --registry-address consul:8500
//
// # etcd
// micro-mcp-gateway --address :3000 --registry etcd --registry-address etcd:2379
//
// # With auth and rate limiting
// micro-mcp-gateway --address :3000 --registry consul \
// --rate-limit 100 --rate-burst 200 --audit
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"
"time"
"go-micro.dev/v6/auth"
"go-micro.dev/v6/auth/jwt"
"go-micro.dev/v6/gateway/mcp"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/registry/consul"
"go-micro.dev/v6/registry/etcd"
"go-micro.dev/v6/wrapper/x402"
"github.com/urfave/cli/v2"
)
var version = "0.1.0"
func main() {
app := &cli.App{
Name: "micro-mcp-gateway",
Usage: "Standalone MCP gateway for go-micro services",
Version: version,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "address",
Usage: "Address to listen on",
Value: ":3000",
EnvVars: []string{"MCP_ADDRESS"},
},
&cli.StringFlag{
Name: "registry",
Usage: "Service registry (mdns, consul, etcd)",
Value: "mdns",
EnvVars: []string{"MICRO_REGISTRY"},
},
&cli.StringFlag{
Name: "registry-address",
Usage: "Registry address (e.g., consul:8500, etcd:2379)",
EnvVars: []string{"MICRO_REGISTRY_ADDRESS"},
},
&cli.StringFlag{
Name: "x402-pay-to",
Usage: "Enable x402 payments for tool calls; the address payments are sent to",
EnvVars: []string{"X402_PAY_TO"},
},
&cli.StringFlag{
Name: "x402-amount",
Usage: "Default amount required per tool call, in the asset's smallest unit (e.g. 10000 = 0.01 USDC)",
EnvVars: []string{"X402_AMOUNT"},
},
&cli.StringFlag{
Name: "x402-network",
Usage: "Payment network: base (default), solana, ...",
Value: "base",
EnvVars: []string{"X402_NETWORK"},
},
&cli.StringFlag{
Name: "x402-facilitator",
Usage: "x402 facilitator URL (Coinbase CDP, Alchemy, or self-hosted)",
EnvVars: []string{"X402_FACILITATOR"},
},
&cli.StringFlag{
Name: "x402-config",
Usage: "Path to an x402 config file (payTo, network, asset, amount, per-tool amounts); overrides the x402-* flags",
EnvVars: []string{"X402_CONFIG"},
},
&cli.Float64Flag{
Name: "rate-limit",
Usage: "Requests per second per tool (0 = unlimited)",
EnvVars: []string{"MCP_RATE_LIMIT"},
},
&cli.IntFlag{
Name: "rate-burst",
Usage: "Rate limit burst size",
Value: 20,
EnvVars: []string{"MCP_RATE_BURST"},
},
&cli.BoolFlag{
Name: "auth",
Usage: "Enable JWT authentication",
EnvVars: []string{"MCP_AUTH"},
},
&cli.BoolFlag{
Name: "audit",
Usage: "Enable audit logging to stdout",
EnvVars: []string{"MCP_AUDIT"},
},
&cli.StringSliceFlag{
Name: "scope",
Usage: "Tool scope requirement (format: tool=scope1,scope2)",
},
&cli.IntFlag{
Name: "circuit-breaker",
Usage: "Circuit breaker max failures before opening (0 = disabled)",
EnvVars: []string{"MCP_CIRCUIT_BREAKER"},
},
&cli.DurationFlag{
Name: "circuit-breaker-timeout",
Usage: "Circuit breaker open-state timeout before half-open probe",
Value: 30 * time.Second,
EnvVars: []string{"MCP_CIRCUIT_BREAKER_TIMEOUT"},
},
},
Action: run,
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func run(c *cli.Context) error {
logger := log.New(os.Stdout, "[mcp-gateway] ", log.LstdFlags)
// Configure registry
reg, err := newRegistry(c.String("registry"), c.String("registry-address"))
if err != nil {
return fmt.Errorf("registry: %w", err)
}
// Build MCP options
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
opts := mcp.Options{
Registry: reg,
Address: c.String("address"),
Context: ctx,
Logger: logger,
}
// Opt-in x402 payments: a config file (per-tool amounts) or flags.
if cfgPath := c.String("x402-config"); cfgPath != "" {
cfg, err := x402.LoadConfig(cfgPath)
if err != nil {
return fmt.Errorf("x402 config: %w", err)
}
opts.Payment = cfg
logger.Printf("x402 payments enabled from %s (payTo %s)", cfgPath, cfg.PayTo)
} else if payTo := c.String("x402-pay-to"); payTo != "" {
opts.Payment = &x402.Config{
PayTo: payTo,
Amount: c.String("x402-amount"),
Network: c.String("x402-network"),
FacilitatorURL: c.String("x402-facilitator"),
}
}
// Rate limiting
if rps := c.Float64("rate-limit"); rps > 0 {
opts.RateLimit = &mcp.RateLimitConfig{
RequestsPerSecond: rps,
Burst: c.Int("rate-burst"),
}
logger.Printf("Rate limit: %.0f req/s, burst %d", rps, c.Int("rate-burst"))
}
// Auth
if c.Bool("auth") {
opts.Auth = jwt.NewAuth()
logger.Printf("JWT authentication enabled")
}
// Scopes
if scopes := c.StringSlice("scope"); len(scopes) > 0 {
opts.Scopes = parseScopes(scopes)
for tool, s := range opts.Scopes {
logger.Printf("Scope: %s requires [%s]", tool, strings.Join(s, ", "))
}
}
// Circuit breaker
if maxFail := c.Int("circuit-breaker"); maxFail > 0 {
opts.CircuitBreaker = &mcp.CircuitBreakerConfig{
MaxFailures: maxFail,
Timeout: c.Duration("circuit-breaker-timeout"),
}
logger.Printf("Circuit breaker: max %d failures, timeout %s", maxFail, c.Duration("circuit-breaker-timeout"))
}
// Audit
if c.Bool("audit") {
opts.AuditFunc = func(r mcp.AuditRecord) {
status := "ALLOWED"
if !r.Allowed {
status = "DENIED:" + r.DeniedReason
}
logger.Printf("[audit] %s tool=%s account=%s status=%s duration=%s",
r.TraceID, r.Tool, r.AccountID, status, r.Duration)
}
logger.Printf("Audit logging enabled")
}
// Print startup info
logger.Printf("Starting MCP gateway on %s", c.String("address"))
logger.Printf("Registry: %s", c.String("registry"))
if addr := c.String("registry-address"); addr != "" {
logger.Printf("Registry address: %s", addr)
}
// Start gateway in background
errCh := make(chan error, 1)
go func() {
errCh <- mcp.ListenAndServe(opts.Address, opts)
}()
// Wait for signal or error
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
select {
case sig := <-sigCh:
logger.Printf("Received %s, shutting down...", sig)
cancel()
return nil
case err := <-errCh:
return fmt.Errorf("gateway error: %w", err)
}
}
func newRegistry(name, address string) (registry.Registry, error) {
var opts []registry.Option
if address != "" {
opts = append(opts, registry.Addrs(strings.Split(address, ",")...))
}
switch name {
case "mdns", "":
return registry.NewMDNSRegistry(opts...), nil
case "consul":
return consul.NewConsulRegistry(opts...), nil
case "etcd":
return etcd.NewEtcdRegistry(opts...), nil
default:
return nil, fmt.Errorf("unknown registry %q (supported: mdns, consul, etcd)", name)
}
}
func parseScopes(raw []string) map[string][]string {
scopes := make(map[string][]string)
for _, s := range raw {
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
continue
}
tool := strings.TrimSpace(parts[0])
scopeList := strings.Split(parts[1], ",")
for i := range scopeList {
scopeList[i] = strings.TrimSpace(scopeList[i])
}
scopes[tool] = scopeList
}
return scopes
}
// Ensure auth.Auth interface is satisfied at compile time.
var _ auth.Auth = jwt.NewAuth()
+41
View File
@@ -22,6 +22,7 @@ import (
"github.com/urfave/cli/v2"
"go-micro.dev/v6/agent"
agentpb "go-micro.dev/v6/agent/proto"
"go-micro.dev/v6/ai"
clt "go-micro.dev/v6/client"
"go-micro.dev/v6/cmd"
@@ -189,6 +190,36 @@ func (s *session) callAgent(ctx context.Context, name, message string) (*agent.R
return r, nil
}
// streamAgent calls an agent's StreamChat endpoint and prints chunks as they
// arrive. Agents that do not expose StreamChat return an error; callers use that
// signal to fall back to Agent.Chat.
func (s *session) streamAgent(ctx context.Context, name, message string) error {
stream, err := agentpb.NewAgentService(name, s.cl).StreamChat(ctx, &agentpb.ChatRequest{Message: message})
if err != nil {
return err
}
defer stream.Close()
var reply strings.Builder
for {
chunk, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return err
}
if chunk == nil || chunk.Reply == "" {
continue
}
fmt.Print(chunk.Reply)
reply.WriteString(chunk.Reply)
}
if reply.Len() > 0 {
fmt.Println()
}
return nil
}
// buildRouterPrompt creates a system prompt for the router that
// knows about all available agents and can dispatch to them.
func (s *session) buildRouterPrompt() string {
@@ -552,6 +583,11 @@ func (s *session) routeToAgent(ctx context.Context, prompt string) error {
if len(s.agents) == 1 {
for name := range s.agents {
fmt.Printf(" \033[35m◆\033[0m \033[2m%s\033[0m\n", name)
if s.stream {
if err := s.streamAgent(ctx, name, prompt); err == nil {
return nil
}
}
resp, err := s.callAgent(ctx, name, prompt)
if err != nil {
return err
@@ -590,6 +626,11 @@ func (s *session) routeToAgent(ctx context.Context, prompt string) error {
}
fmt.Printf(" \033[35m◆\033[0m \033[2m%s\033[0m\n", agentName)
if s.stream {
if err := s.streamAgent(ctx, agentName, message); err == nil {
return ai.ToolResult{ID: call.ID, Value: map[string]string{"agent": agentName, "streamed": "true"}, Content: `{"streamed":true}`}
}
}
resp, err := s.callAgent(ctx, agentName, message)
if err != nil {
return ai.ToolResult{ID: call.ID, Value: map[string]string{"error": err.Error()}, Content: `{"error":"` + err.Error() + `"}`}
+96 -1
View File
@@ -2,14 +2,17 @@
package agent
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"time"
"github.com/urfave/cli/v2"
goagent "go-micro.dev/v6/agent"
"go-micro.dev/v6/cmd"
aiflow "go-micro.dev/v6/flow"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
)
@@ -192,6 +195,23 @@ history, and no-secret fallback checks.`,
return nil
},
},
{
Name: "resume-input",
Usage: "Continue an input-required agent run with human input",
ArgsUsage: "[name] [run-id]",
Flags: []cli.Flag{
&cli.StringFlag{Name: "input", Usage: "Human input to provide to the paused run", Required: true},
},
Action: func(c *cli.Context) error {
name := c.Args().First()
runID := c.Args().Get(1)
if name == "" || runID == "" {
return fmt.Errorf("usage: micro agent resume-input [name] [run-id] --input <text>")
}
return resumeInputRun(context.Background(), c.App.Writer, name, runID, c.String("input"))
},
},
{
Name: "history",
Usage: "Show an agent's stored conversation and run history",
@@ -285,7 +305,7 @@ func writeRunIndex(w io.Writer, name string, runs []goagent.RunSummary, asJSON b
func writeRunIndexBreadcrumbs(w io.Writer, name string, run goagent.RunSummary) {
if run.Stage == "input-required" {
fmt.Fprintf(w, " inspect: micro agent history %s %s\n", name, run.RunID)
fmt.Fprintf(w, " input: call micro.AgentResumeInput(ctx, agent, %q, input) to continue the input-required run\n", run.RunID)
fmt.Fprintf(w, " input: micro agent resume-input %s %s --input <text>\n", name, run.RunID)
return
}
if !isResumableRunSummary(run) {
@@ -370,3 +390,78 @@ func shortTraceID(id string) string {
}
return id[:12]
}
type cliInputPause struct {
OriginalMessage string `json:"original_message"`
Prompt string `json:"prompt"`
}
func resumeInputRun(ctx context.Context, w io.Writer, name, runID, input string) error {
if input == "" {
return fmt.Errorf("input required: pass --input <text>")
}
cp := aiflow.StoreCheckpoint(store.DefaultStore, name)
run, ok, err := cp.Load(ctx, runID)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("agent run %s not found for %q", runID, name)
}
if run.Status != "paused" || run.State.Stage != "input-required" {
return fmt.Errorf("agent run %s is not waiting for human input", runID)
}
var pause cliInputPause
_ = run.State.Scan(&pause)
reply := "Human input recorded; recreate the agent with the same checkpoint store and call micro.AgentResumeInput to continue model execution."
resp := goagent.Response{Reply: reply, Agent: name, RunID: runID, ParentID: run.ParentID}
data, err := json.Marshal(resp)
if err != nil {
return err
}
run.Status = "done"
run.State.Stage = "done"
run.State.Data = data
for i := range run.Steps {
if run.Steps[i].Status == "paused" || run.Steps[i].Name == "ask" {
run.Steps[i].Status = "done"
run.Steps[i].Error = ""
run.Steps[i].Result = "human input: " + input
}
}
if len(run.Steps) == 0 {
run.Steps = []aiflow.StepRecord{{Name: "ask", Status: "done", Result: "human input: " + input}}
}
if err := cp.Save(ctx, run); err != nil {
return err
}
if err := recordCLIResumeEvents(name, runID, run.ParentID); err != nil {
return err
}
if pause.Prompt != "" {
fmt.Fprintf(w, " Prompt: %s\n", pause.Prompt)
}
fmt.Fprintf(w, " Recorded input for agent %q run %s.\n", name, runID)
fmt.Fprintf(w, " Inspect: micro inspect agent %s --limit 1\n", name)
return nil
}
func recordCLIResumeEvents(name, runID, parentID string) error {
now := time.Now()
scoped := store.Scope(store.DefaultStore, "agent", name)
events := []goagent.RunEvent{
{Time: now, RunID: runID, ParentID: parentID, Agent: name, Kind: "checkpoint", Name: "done", Status: "done"},
{Time: now.Add(time.Nanosecond), RunID: runID, ParentID: parentID, Agent: name, Kind: "done"},
}
for _, e := range events {
b, err := json.Marshal(e)
if err != nil {
return err
}
key := fmt.Sprintf("runs/%s/%020d-%s", runID, e.Time.UnixNano(), e.Kind)
if err := scoped.Write(&store.Record{Key: key, Value: b}); err != nil {
return err
}
}
return nil
}
+42 -1
View File
@@ -2,6 +2,7 @@ package agent
import (
"bytes"
"context"
"encoding/json"
"strings"
"testing"
@@ -9,6 +10,8 @@ import (
goagent "go-micro.dev/v6/agent"
"go-micro.dev/v6/ai"
aiflow "go-micro.dev/v6/flow"
"go-micro.dev/v6/store"
)
func TestWriteRunIndexJSON(t *testing.T) {
@@ -89,7 +92,7 @@ func TestWriteRunIndexInputRequiredUsesResumeInput(t *testing.T) {
t.Fatal(err)
}
got := out.String()
for _, want := range []string{`micro agent history runner run-input`, `micro.AgentResumeInput(ctx, agent, "run-input", input)`} {
for _, want := range []string{`micro agent history runner run-input`, `micro agent resume-input runner run-input --input <text>`} {
if !strings.Contains(got, want) {
t.Fatalf("output missing %q:\n%s", want, got)
}
@@ -137,3 +140,41 @@ func TestWriteRunHistoryHumanAndJSON(t *testing.T) {
t.Fatalf("decoded events = %#v", got)
}
}
func TestResumeInputRunCompletesCheckpointAndInspectSummary(t *testing.T) {
oldStore := store.DefaultStore
store.DefaultStore = store.NewMemoryStore()
t.Cleanup(func() { store.DefaultStore = oldStore })
ctx := context.Background()
cp := aiflow.StoreCheckpoint(store.DefaultStore, "runner")
run := aiflow.Run{ID: "run-input", Flow: "runner", Status: "paused", State: aiflow.State{Stage: "input-required"}, Steps: []aiflow.StepRecord{{Name: "ask", Status: "paused", Error: "Which region?"}}}
if err := run.State.Set(cliInputPause{OriginalMessage: "deploy", Prompt: "Which region?"}); err != nil {
t.Fatalf("set pause: %v", err)
}
if err := cp.Save(ctx, run); err != nil {
t.Fatalf("save checkpoint: %v", err)
}
var out bytes.Buffer
if err := resumeInputRun(ctx, &out, "runner", "run-input", "us-east-1"); err != nil {
t.Fatalf("resumeInputRun: %v", err)
}
if got := out.String(); !strings.Contains(got, "Recorded input") || !strings.Contains(got, "micro inspect agent runner --limit 1") {
t.Fatalf("output missing continuation hints:\n%s", got)
}
loaded, ok, err := cp.Load(ctx, "run-input")
if err != nil || !ok {
t.Fatalf("load checkpoint ok=%v err=%v", ok, err)
}
if loaded.Status != "done" || loaded.State.Stage != "done" {
t.Fatalf("loaded run status/stage = %s/%s, want done/done", loaded.Status, loaded.State.Stage)
}
summaries, err := goagent.ListRunSummariesWithOptions(store.DefaultStore, "runner", goagent.RunListOptions{Status: "done"})
if err != nil {
t.Fatalf("summaries: %v", err)
}
if len(summaries) != 1 || summaries[0].RunID != "run-input" || summaries[0].Status != "done" {
t.Fatalf("summaries = %#v, want completed run-input", summaries)
}
}
+16 -8
View File
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/urfave/cli/v2"
microcmd "go-micro.dev/v6/cmd"
)
@@ -207,7 +208,7 @@ func TestFirstAgentDocsMatchCLIOutput(t *testing.T) {
},
{
name: "website getting-started first-agent on-ramp",
file: filepath.Join(root, "internal", "website", "docs", "getting-started.md"),
file: filepath.Join(root, "internal", "website", "content", "en", "docs", "getting-started", "index.md"),
markers: []string{
"micro agent demo",
"micro agent quickcheck",
@@ -219,10 +220,10 @@ func TestFirstAgentDocsMatchCLIOutput(t *testing.T) {
"make docs-wayfinding",
"github.com/micro/go-micro/tree/master/examples/first-agent",
"github.com/micro/go-micro/tree/master/examples/support",
"guides/no-secret-first-agent.html",
"guides/your-first-agent.html",
"guides/debugging-agents.html",
"guides/zero-to-hero.html",
"guides/no-secret-first-agent.md",
"guides/your-first-agent.md",
"guides/debugging-agents.md",
"guides/zero-to-hero.md",
},
},
}
@@ -233,8 +234,11 @@ func TestFirstAgentDocsMatchCLIOutput(t *testing.T) {
if !strings.Contains(doc, marker) {
t.Fatalf("%s missing documented first-agent marker %q", contract.name, marker)
}
if isCLIContractMarker(marker) && !cliOutputsContain(outputs, marker) {
t.Fatalf("%s documents %q, but none of the first-agent CLI outputs mention it; keep README/website breadcrumbs aligned with micro agent demo/examples/zero-to-hero", contract.name, marker)
if isCLIContractMarker(marker) {
cliMarker := strings.ReplaceAll(marker, ".md", ".html")
if !cliOutputsContain(outputs, cliMarker) {
t.Fatalf("%s documents %q, but none of the first-agent CLI outputs mention it; keep README/website breadcrumbs aligned with micro agent demo/examples/zero-to-hero", contract.name, marker)
}
}
assertMaintainedFirstAgentPath(t, root, marker)
}
@@ -262,7 +266,7 @@ func cliOutputsContain(outputs map[string]string, marker string) bool {
}
func isCLIContractMarker(marker string) bool {
return strings.HasPrefix(marker, "micro ") || strings.HasPrefix(marker, "go run ") || strings.HasPrefix(marker, "go test ") || strings.Contains(marker, ".html")
return strings.HasPrefix(marker, "micro ") || strings.HasPrefix(marker, "go run ") || strings.HasPrefix(marker, "go test ") || strings.HasPrefix(marker, "guides/") || strings.Contains(marker, ".html")
}
func assertMaintainedFirstAgentPath(t *testing.T, root, marker string) {
@@ -279,6 +283,10 @@ func assertMaintainedFirstAgentPath(t *testing.T, root, marker string) {
"guides/your-first-agent.html": "internal/website/docs/guides/your-first-agent.md",
"guides/debugging-agents.html": "internal/website/docs/guides/debugging-agents.md",
"guides/zero-to-hero.html": "internal/website/docs/guides/zero-to-hero.md",
"guides/no-secret-first-agent.md": "internal/website/content/en/docs/guides/no-secret-first-agent.md",
"guides/your-first-agent.md": "internal/website/content/en/docs/guides/your-first-agent.md",
"guides/debugging-agents.md": "internal/website/content/en/docs/guides/debugging-agents.md",
"guides/zero-to-hero.md": "internal/website/content/en/docs/guides/zero-to-hero.md",
"github.com/micro/go-micro/tree/master/examples/first-agent": "examples/first-agent",
"github.com/micro/go-micro/tree/master/examples/support": "examples/support",
}
+128
View File
@@ -0,0 +1,128 @@
package gateway
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"net"
"net/http"
"os"
"strings"
"github.com/urfave/cli/v2"
)
// authToken is the static machine token accepted as an admin ("*" scope)
// credential, alongside JWTs. Empty means JWT-only. It is minted (or supplied)
// once per process — never a fixed default like admin/micro.
var authToken string
// isExposed reports whether a bind address is reachable beyond loopback. An
// empty host (":8080"), 0.0.0.0, and :: bind all interfaces and are exposed;
// 127.0.0.1 / localhost / ::1 are not. Unclassifiable hostnames are treated as
// exposed (fail safe).
func isExposed(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = strings.Trim(addr, "[]")
}
switch strings.ToLower(host) {
case "", "0.0.0.0", "::":
return true
case "localhost":
return false
}
if ip := net.ParseIP(host); ip != nil {
return !ip.IsLoopback()
}
return true
}
// AuthFlags are the auth-policy flags shared by `micro run` and `micro gateway`.
func AuthFlags() []cli.Flag {
return []cli.Flag{
&cli.BoolFlag{
Name: "auth",
Usage: "Force authentication on (default: on when the bind address is non-loopback)",
},
&cli.BoolFlag{
Name: "no-auth",
Usage: "Force authentication off",
},
&cli.StringFlag{
Name: "auth-token",
Usage: "Static bearer token to require; if omitted while auth is on, one is generated and printed once",
EnvVars: []string{"MICRO_AUTH_TOKEN"},
},
}
}
// ResolveAuth decides whether the gateway on addr requires authentication and
// provisions the machine token. The default follows the socket — auth is on
// when addr is exposed, off on loopback — and is overridable with --auth /
// --no-auth or MICRO_AUTH=on|off. A token is always provisioned (supplied via
// --auth-token/MICRO_AUTH_TOKEN, else generated) so that scoped/paid tools stay
// reachable even in auth-off mode; the returned string is non-empty only when a
// token was generated and should be printed once.
func ResolveAuth(c *cli.Context, addr string) (enabled bool, generatedToken string) {
switch strings.ToLower(authOverride(c)) {
case "off", "false", "no", "0":
enabled = false
case "on", "true", "yes", "1":
enabled = true
default:
enabled = isExposed(addr)
}
if tok := c.String("auth-token"); tok != "" {
authToken = tok
} else if authToken == "" {
authToken = generateToken()
generatedToken = authToken
}
return enabled, generatedToken
}
func authOverride(c *cli.Context) string {
if c.Bool("no-auth") {
return "off"
}
if c.Bool("auth") {
return "on"
}
return os.Getenv("MICRO_AUTH")
}
func generateToken() string {
b := make([]byte, 24)
if _, err := rand.Read(b); err != nil {
// crypto/rand should never fail; fall back is still unique per process.
return hex.EncodeToString([]byte(os.Args[0]))
}
return hex.EncodeToString(b)
}
// tokenMatches reports whether tok equals the static machine token in constant
// time. An empty static token or empty tok never matches.
func tokenMatches(tok string) bool {
if authToken == "" || tok == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(tok), []byte(authToken)) == 1
}
// extractToken pulls a bearer token from the request: Authorization header
// first, then a `token` query parameter (for SSE / browser links), then the
// micro_token cookie.
func extractToken(r *http.Request) string {
if authz := r.Header.Get("Authorization"); strings.HasPrefix(authz, "Bearer ") {
return strings.TrimSpace(strings.TrimPrefix(authz, "Bearer "))
}
if q := r.URL.Query().Get("token"); q != "" {
return q
}
if cookie, err := r.Cookie("micro_token"); err == nil {
return cookie.Value
}
return ""
}
+86
View File
@@ -0,0 +1,86 @@
package gateway
import (
"flag"
"testing"
"github.com/urfave/cli/v2"
)
func TestIsExposed(t *testing.T) {
cases := map[string]bool{
":8080": true, // empty host = all interfaces
"0.0.0.0:8080": true, // all interfaces
"[::]:8080": true, // all interfaces (v6)
"192.168.1.10:80": true, // routable
"example.com:8080": true, // hostname we can't classify → fail safe
"127.0.0.1:8080": false, // loopback
"localhost:8080": false, // loopback
"[::1]:8080": false, // loopback (v6)
}
for addr, want := range cases {
if got := isExposed(addr); got != want {
t.Errorf("isExposed(%q) = %v, want %v", addr, got, want)
}
}
}
func newCtx(t *testing.T, token string, auth, noAuth bool) *cli.Context {
t.Helper()
set := flag.NewFlagSet("test", flag.ContinueOnError)
set.String("auth-token", token, "")
set.Bool("auth", auth, "")
set.Bool("no-auth", noAuth, "")
return cli.NewContext(nil, set, nil)
}
func TestResolveAuthDefaultFollowsAddress(t *testing.T) {
authToken = ""
if enabled, _ := ResolveAuth(newCtx(t, "", false, false), "127.0.0.1:8080"); enabled {
t.Fatal("loopback should default to auth off")
}
authToken = ""
if enabled, _ := ResolveAuth(newCtx(t, "", false, false), ":8080"); !enabled {
t.Fatal("exposed address should default to auth on")
}
}
func TestResolveAuthOverrides(t *testing.T) {
authToken = ""
if enabled, _ := ResolveAuth(newCtx(t, "", false, true), ":8080"); enabled {
t.Fatal("--no-auth must force auth off even when exposed")
}
authToken = ""
if enabled, _ := ResolveAuth(newCtx(t, "", true, false), "127.0.0.1:8080"); !enabled {
t.Fatal("--auth must force auth on even on loopback")
}
}
func TestResolveAuthToken(t *testing.T) {
// Supplied token is used verbatim and not echoed for printing.
authToken = ""
_, gen := ResolveAuth(newCtx(t, "supplied-secret", true, false), ":8080")
if gen != "" {
t.Fatalf("supplied token should not be returned for printing, got %q", gen)
}
if authToken != "supplied-secret" {
t.Fatalf("authToken = %q, want the supplied secret", authToken)
}
if !tokenMatches("supplied-secret") || tokenMatches("wrong") {
t.Fatal("tokenMatches should accept the supplied token and reject others")
}
// No token supplied → one is generated and returned to print once.
authToken = ""
_, gen = ResolveAuth(newCtx(t, "", true, false), ":8080")
if gen == "" || gen != authToken {
t.Fatalf("expected a generated token to be returned and stored, got gen=%q authToken=%q", gen, authToken)
}
}
func TestTokenMatchesEmpty(t *testing.T) {
authToken = ""
if tokenMatches("") || tokenMatches("anything") {
t.Fatal("an empty static token must never match")
}
}
@@ -1,4 +1,4 @@
package server
package gateway
import (
"fmt"
@@ -1,4 +1,4 @@
package server
package gateway
import (
"context"
@@ -14,6 +14,7 @@ import (
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"sort"
"strconv"
@@ -33,12 +34,16 @@ import (
_ "go-micro.dev/v6/ai/openai"
_ "go-micro.dev/v6/ai/together"
"go-micro.dev/v6/auth"
"go-micro.dev/v6/auth/jwt"
"go-micro.dev/v6/client"
"go-micro.dev/v6/cmd"
codecBytes "go-micro.dev/v6/codec/bytes"
"go-micro.dev/v6/gateway/mcp"
"go-micro.dev/v6/registry"
"go-micro.dev/v6/store"
"go-micro.dev/v6/wrapper/x402"
"golang.org/x/crypto/bcrypt"
"golang.org/x/sync/errgroup"
)
// HTML is the embedded filesystem for templates and static files, set by main.go
@@ -161,20 +166,7 @@ func deleteUserTokens(storeInst store.Store, userID string) {
func authRequired(storeInst store.Store) func(http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var token string
// 1. Check Authorization: Bearer header
authz := r.Header.Get("Authorization")
if strings.HasPrefix(authz, "Bearer ") {
token = strings.TrimPrefix(authz, "Bearer ")
token = strings.TrimSpace(token)
}
// 2. Fallback to micro_token cookie if no header
if token == "" {
cookie, err := r.Cookie("micro_token")
if err == nil && cookie.Value != "" {
token = cookie.Value
}
}
token := extractToken(r)
if token == "" {
if strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != "/api" && r.URL.Path != "/api/" {
w.Header().Set("Content-Type", "application/json")
@@ -191,6 +183,11 @@ func authRequired(storeInst store.Store) func(http.HandlerFunc) http.HandlerFunc
http.Redirect(w, r, "/auth/login", http.StatusFound)
return
}
// A matching static machine token authenticates as admin.
if tokenMatches(token) {
next(w, r)
return
}
claims, err := ParseJWT(token)
if err != nil {
if strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != "/api" && r.URL.Path != "/api/" {
@@ -332,9 +329,10 @@ func registerHandlers(mux *http.ServeMux, tmpls *templates, storeInst store.Stor
// required scopes for a service endpoint. Returns true if allowed.
// If not allowed, writes a 403 response and returns false.
checkEndpointScopes := func(w http.ResponseWriter, r *http.Request, endpointKey string) bool {
if !authEnabled {
return true
}
// Scope enforcement is independent of the auth on/off decision: an
// endpoint that declares a required scope always needs a token bearing
// it, even on a loopback gateway with auth off. That is what keeps
// action/paid tools gated locally while read-only tools stay open.
recs, _ := storeInst.Read("endpoint-scopes/" + endpointKey)
if len(recs) == 0 {
return true // no scopes configured = unrestricted
@@ -343,17 +341,13 @@ func registerHandlers(mux *http.ServeMux, tmpls *templates, storeInst store.Stor
if err := json.Unmarshal(recs[0].Value, &requiredScopes); err != nil || len(requiredScopes) == 0 {
return true
}
// A matching static machine token is admin (all scopes).
token := extractToken(r)
if tokenMatches(token) {
return true
}
// Extract caller's scopes from JWT
callerScopes := []string{}
token := ""
if authz := r.Header.Get("Authorization"); strings.HasPrefix(authz, "Bearer ") {
token = strings.TrimPrefix(authz, "Bearer ")
}
if token == "" {
if cookie, err := r.Cookie("micro_token"); err == nil {
token = cookie.Value
}
}
if token != "" {
if claims, err := ParseJWT(token); err == nil {
if s, ok := claims["scopes"].([]interface{}); ok {
@@ -900,14 +894,74 @@ func registerHandlers(mux *http.ServeMux, tmpls *templates, storeInst store.Stor
apiCache.time = time.Now()
}
apiCache.Unlock()
// Add API auth doc at the top
apiData["ApiAuthDoc"] = `<div style='background:#f8f8e8; border:1px solid #e0e0b0; padding:1em; margin-bottom:2em; font-size:1.08em;'>
<b>API Authentication Required:</b> All API calls to <code>/api/...</code> endpoints (except this page) must include an <b>Authorization: Bearer &lt;token&gt;</b> header. <br>
You can generate tokens on the <a href='/auth/tokens'>Tokens page</a>.
// Add API auth doc at the top — reflects the address-based policy.
if authEnabled {
apiData["ApiAuthDoc"] = `<div style='background:#f8f8e8; border:1px solid #e0e0b0; padding:1em; margin-bottom:2em; font-size:1.08em;'>
<b>Authentication required:</b> this gateway is exposed, so all <code>/api/...</code> calls must include an <b>Authorization: Bearer &lt;token&gt;</b> header (or <code>?token=</code>). <br>
Use the token printed at startup, or generate more on the <a href='/auth/tokens'>Tokens page</a>.
</div>`
} else {
apiData["ApiAuthDoc"] = `<div style='background:#eef6ee; border:1px solid #bcd8bc; padding:1em; margin-bottom:2em; font-size:1.08em;'>
<b>Auth is off</b> (gateway on loopback) call <code>/api/...</code> directly, no token needed. Tools with a required <a href='/auth/scopes'>scope</a> (actions, paid) still need a token.
</div>`
}
_ = renderPage(w, tmpls.api, apiData)
return
}
// HTTP->RPC proxy: /api/{service}/{method} (e.g. /api/helloworld/Helloworld.Call)
// also accepts /api/{service}/{pkg}/{method} as linked from the API explorer.
if strings.HasPrefix(path, "/api/") {
parts := strings.Split(strings.TrimPrefix(path, "/api/"), "/")
var service, endpoint string
switch len(parts) {
case 2:
service, endpoint = parts[0], parts[1]
case 3:
service, endpoint = parts[0], parts[1]+"."+parts[2]
default:
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Not found"))
return
}
svcs, err := registry.GetService(service)
if err != nil || len(svcs) == 0 {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Service not found: " + service))
return
}
valid := false
for _, ep := range svcs[0].Endpoints {
if ep.Name == endpoint {
valid = true
break
}
}
if !valid {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("Endpoint not found: " + endpoint))
return
}
if !checkEndpointScopes(w, r, service+"."+endpoint) {
return
}
inputBytes, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
rpcReq := client.DefaultClient.NewRequest(service, endpoint, &codecBytes.Frame{Data: inputBytes})
var rsp codecBytes.Frame
if err := client.DefaultClient.Call(r.Context(), rpcReq, &rsp); err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadGateway)
w.Write([]byte(`{"error":` + strconv.Quote(err.Error()) + `}`))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(rsp.Data)
return
}
if path == "/services" {
// Do NOT include SidebarEndpoints on this page
services, _ := registry.ListServices()
@@ -1499,16 +1553,157 @@ func Run(c *cli.Context) error {
mcpAddr := c.String("mcp-address")
// Run the gateway with authentication enabled
// Auth follows the socket: on when the bind address is exposed, off on
// loopback, overridable with --auth/--no-auth. When on, a machine token is
// provisioned (supplied or generated); print a generated one once.
authEnabled, genToken := ResolveAuth(c, addr)
// Run the HTTP gateway (dashboard, REST, auth).
opts := GatewayOptions{
Address: addr,
AuthEnabled: true,
AuthEnabled: authEnabled,
Context: c.Context,
MCPEnabled: mcpAddr != "",
MCPAddress: mcpAddr,
}
return RunGateway(opts)
if authEnabled {
if genToken != "" {
log.Printf("[auth] on (%s is exposed). Token (shown once): %s", addr, genToken)
} else {
log.Printf("[auth] on (%s is exposed). Using supplied MICRO_AUTH_TOKEN.", addr)
}
} else {
log.Printf("[auth] off (%s is loopback). Scoped/paid tools still require a token.", addr)
}
// The MCP gateway runs independently of the HTTP API gateway, carrying the
// production controls (rate limiting, scopes, auth, audit, circuit breaker,
// x402 payments). Both gateways are started explicitly below and shut down
// together when the first one exits or a signal arrives.
var mcpServer *mcp.Server
if mcpAddr != "" {
mcpOpts, err := buildMCPOptions(c, mcpAddr)
if err != nil {
return err
}
mcpServer, err = mcp.NewServer(mcpOpts)
if err != nil {
return fmt.Errorf("failed to start MCP gateway: %w", err)
}
log.Printf("[mcp] gateway on %s", mcpAddr)
}
gw, err := StartGateway(opts)
if err != nil {
return fmt.Errorf("failed to start gateway: %w", err)
}
// Run both gateways until a signal or the first gateway exits.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
var eg errgroup.Group
eg.Go(func() error { return gw.Wait() })
if mcpServer != nil {
eg.Go(func() error { return mcpServer.Serve() })
}
errCh := make(chan error, 1)
go func() { errCh <- eg.Wait() }()
select {
case <-sigCh:
log.Printf("[gateway] shutting down")
case err = <-errCh:
log.Printf("[gateway] gateway exited: %v", err)
}
_ = gw.Stop()
if mcpServer != nil {
_ = mcpServer.Stop()
}
return err
}
// buildMCPOptions assembles the MCP gateway options from the command flags. It
// carries the same production controls the standalone gateway binary had.
func buildMCPOptions(c *cli.Context, addr string) (mcp.Options, error) {
logger := log.New(os.Stdout, "[mcp-gateway] ", log.LstdFlags)
opts := mcp.Options{
Registry: registry.DefaultRegistry,
Address: addr,
Context: c.Context,
Logger: logger,
}
// x402 payments: a config file (per-tool amounts) or the flags.
if cfgPath := c.String("x402-config"); cfgPath != "" {
cfg, err := x402.LoadConfig(cfgPath)
if err != nil {
return opts, fmt.Errorf("x402 config: %w", err)
}
opts.Payment = cfg
logger.Printf("x402 payments enabled from %s (payTo %s)", cfgPath, cfg.PayTo)
} else if payTo := c.String("x402-pay-to"); payTo != "" {
opts.Payment = &x402.Config{
PayTo: payTo,
Amount: c.String("x402-amount"),
Network: c.String("x402-network"),
FacilitatorURL: c.String("x402-facilitator"),
}
}
if rps := c.Float64("rate-limit"); rps > 0 {
opts.RateLimit = &mcp.RateLimitConfig{RequestsPerSecond: rps, Burst: c.Int("rate-burst")}
logger.Printf("rate limit: %.0f req/s, burst %d", rps, c.Int("rate-burst"))
}
if c.Bool("auth") {
opts.Auth = jwt.NewAuth()
logger.Printf("JWT authentication enabled")
}
if scopes := c.StringSlice("scope"); len(scopes) > 0 {
opts.Scopes = parseScopes(scopes)
}
if maxFail := c.Int("circuit-breaker"); maxFail > 0 {
opts.CircuitBreaker = &mcp.CircuitBreakerConfig{
MaxFailures: maxFail,
Timeout: c.Duration("circuit-breaker-timeout"),
}
}
if c.Bool("audit") {
opts.AuditFunc = func(r mcp.AuditRecord) {
status := "ALLOWED"
if !r.Allowed {
status = "DENIED:" + r.DeniedReason
}
logger.Printf("[audit] %s tool=%s account=%s status=%s duration=%s",
r.TraceID, r.Tool, r.AccountID, status, r.Duration)
}
logger.Printf("audit logging enabled")
}
return opts, nil
}
// parseScopes turns "tool=scope1,scope2" flag values into a tool→scopes map.
func parseScopes(raw []string) map[string][]string {
scopes := make(map[string][]string)
for _, s := range raw {
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
continue
}
tool := strings.TrimSpace(parts[0])
scopeList := strings.Split(parts[1], ",")
for i := range scopeList {
scopeList[i] = strings.TrimSpace(scopeList[i])
}
scopes[tool] = scopeList
}
return scopes
}
// mapGoTypeToJSON maps Go types to JSON schema types
@@ -1561,30 +1756,10 @@ func initAuth() error {
}
_, _ = os.ReadFile(privPath)
_, _ = os.ReadFile(pubPath)
storeInst := store.DefaultStore
// --- Ensure default admin account exists on first run ---
// If the admin was explicitly deleted (marker key exists), don't recreate.
adminID := "admin"
adminPass := "micro"
adminKey := "auth/" + adminID
adminDeletedKey := "auth/.admin-deleted"
if recs, _ := storeInst.Read(adminDeletedKey); len(recs) > 0 {
// Admin was explicitly deleted — don't recreate
} else if recs, _ := storeInst.Read(adminKey); len(recs) == 0 {
// Hash the admin password with bcrypt
hash, err := bcrypt.GenerateFromPassword([]byte(adminPass), bcrypt.DefaultCost)
if err != nil {
return err
}
acc := &Account{
ID: adminID,
Type: "admin",
Scopes: []string{"*"},
Metadata: map[string]string{"created": time.Now().Format(time.RFC3339), "password_hash": string(hash)},
}
b, _ := json.Marshal(acc)
_ = storeInst.Write(&store.Record{Key: adminKey, Value: b})
}
// No default credential is created. The gateway authenticates with the
// per-process machine token (see ResolveAuth) plus any accounts/tokens an
// operator creates via /auth. A guessable admin/micro would be friction and
// no security at once.
return nil
}
@@ -1592,23 +1767,115 @@ func initAuth() error {
func parseStartTime(s string) (time.Time, error) {
return time.Parse(time.RFC3339, s)
}
// gatewayFlags are shared by `micro gateway` and its deprecated `server` alias.
func gatewayFlags() []cli.Flag {
flags := []cli.Flag{
&cli.StringFlag{
Name: "address",
Usage: "HTTP address for the dashboard/API",
EnvVars: []string{"MICRO_SERVER_ADDRESS"},
Value: ":8080",
},
&cli.StringFlag{
Name: "mcp-address",
Usage: "MCP protocol address (e.g., :3000). Enables the MCP gateway for AI tools.",
EnvVars: []string{"MICRO_MCP_ADDRESS"},
},
&cli.Float64Flag{
Name: "rate-limit",
Usage: "MCP: requests per second per tool (0 = unlimited)",
EnvVars: []string{"MCP_RATE_LIMIT"},
},
&cli.IntFlag{
Name: "rate-burst",
Usage: "MCP: rate limit burst size",
Value: 20,
EnvVars: []string{"MCP_RATE_BURST"},
},
&cli.BoolFlag{
Name: "audit",
Usage: "MCP: enable audit logging to stdout",
EnvVars: []string{"MCP_AUDIT"},
},
&cli.StringSliceFlag{
Name: "scope",
Usage: "MCP: tool scope requirement (format: tool=scope1,scope2)",
},
&cli.IntFlag{
Name: "circuit-breaker",
Usage: "MCP: circuit breaker max failures before opening (0 = disabled)",
EnvVars: []string{"MCP_CIRCUIT_BREAKER"},
},
&cli.DurationFlag{
Name: "circuit-breaker-timeout",
Usage: "MCP: circuit breaker open-state timeout before half-open probe",
Value: 30 * time.Second,
EnvVars: []string{"MCP_CIRCUIT_BREAKER_TIMEOUT"},
},
&cli.StringFlag{
Name: "x402-pay-to",
Usage: "MCP: enable x402 payments for tool calls; the address payments are sent to",
EnvVars: []string{"X402_PAY_TO"},
},
&cli.StringFlag{
Name: "x402-amount",
Usage: "MCP: default amount required per tool call, in the asset's smallest unit (e.g. 10000 = 0.01 USDC)",
EnvVars: []string{"X402_AMOUNT"},
},
&cli.StringFlag{
Name: "x402-network",
Usage: "MCP: payment network: base (default), solana, ...",
Value: "base",
EnvVars: []string{"X402_NETWORK"},
},
&cli.StringFlag{
Name: "x402-facilitator",
Usage: "MCP: x402 facilitator URL (Coinbase CDP, Alchemy, or self-hosted)",
EnvVars: []string{"X402_FACILITATOR"},
},
&cli.StringFlag{
Name: "x402-config",
Usage: "MCP: path to an x402 config file; overrides the x402-* flags",
EnvVars: []string{"X402_CONFIG"},
},
}
return append(flags, AuthFlags()...)
}
func init() {
cmd.Register(&cli.Command{
Name: "server",
Usage: "Production mode: run the micro server with dashboard and auth",
Name: "gateway",
Usage: "Run the gateway: HTTP API, dashboard, auth, and MCP tools for your services",
Description: `Run the gateway in front of your running services.
It serves an HTTP API and dashboard (with auth) on --address, and when
--mcp-address is set an MCP gateway that exposes every discovered service as
an AI-callable tool, with optional rate limiting, scopes, JWT auth, audit
logging, circuit breaking, and x402 payments.
Services are discovered through the registry (select it with the global
--registry / --registry_address flags). This is the gateway you deploy in
production; for the local development loop use ` + "`micro run`" + `.
Examples:
micro gateway # dashboard/API on :8080
micro gateway --mcp-address :3000 # + MCP gateway on :3000
micro gateway --mcp-address :3000 --auth --audit --rate-limit 100
micro gateway --registry consul --registry_address consul:8500 --mcp-address :3000`,
Action: Run,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "address",
Usage: "Address to listen on",
EnvVars: []string{"MICRO_SERVER_ADDRESS"},
Value: ":8080",
},
&cli.StringFlag{
Name: "mcp-address",
Usage: "MCP gateway address (e.g., :3000). Enables MCP protocol support for AI tools.",
EnvVars: []string{"MICRO_MCP_ADDRESS"},
},
Flags: gatewayFlags(),
})
// Deprecated alias: `micro server` still works but is hidden and warns.
cmd.Register(&cli.Command{
Name: "server",
Hidden: true,
Usage: "Deprecated alias for `micro gateway`",
Action: func(c *cli.Context) error {
fmt.Fprintln(os.Stderr, "warning: `micro server` is deprecated and will be removed; use `micro gateway`")
return Run(c)
},
Flags: gatewayFlags(),
})
}
@@ -1,4 +1,4 @@
package server
package gateway
import (
"crypto/rand"
+8 -2
View File
@@ -43,7 +43,7 @@ It reads durable local run history, so it works after the agent or flow has stop
func inspectAgentFlags() []cli.Flag {
return []cli.Flag{
&cli.BoolFlag{Name: "json", Usage: "Print run summaries as JSON for automation"},
&cli.StringFlag{Name: "status", Usage: "Only show runs with this status (running, done, error, refused)"},
&cli.StringFlag{Name: "status", Usage: "Only show runs with this status (running, done, canceled, timeout, rate_limited, auth, configuration, unavailable, provider_error, error, refused)"},
&cli.StringFlag{Name: "trace", Usage: "Only show runs whose trace id matches this full id or prefix"},
&cli.IntFlag{Name: "limit", Usage: "Show the most recently updated N runs"},
}
@@ -91,6 +91,12 @@ func writeAgentInspection(w io.Writer, name string, runs []goagent.RunSummary, a
if run.Stage != "" {
fmt.Fprintf(w, " stage=%s", run.Stage)
}
if run.LastErrorKind != "" {
fmt.Fprintf(w, " error_kind=%s", run.LastErrorKind)
}
if run.Spent > 0 {
fmt.Fprintf(w, " spent=%d", run.Spent)
}
if run.LastError != "" {
fmt.Fprintf(w, " error=%q", run.LastError)
}
@@ -106,7 +112,7 @@ func writeAgentInspection(w io.Writer, name string, runs []goagent.RunSummary, a
func writeAgentRunBreadcrumbs(w io.Writer, name string, run goagent.RunSummary) {
if run.Stage == "input-required" {
fmt.Fprintf(w, " inspect: micro agent history %s %s\n", name, run.RunID)
fmt.Fprintf(w, " input: call micro.AgentResumeInput(ctx, agent, %q, input) to continue the input-required run\n", run.RunID)
fmt.Fprintf(w, " input: micro agent resume-input %s %s --input <text>\n", name, run.RunID)
return
}
if !isResumableAgentRun(run) {
+3 -3
View File
@@ -11,13 +11,13 @@ import (
)
func TestWriteAgentInspectionIncludesActionableBreadcrumbs(t *testing.T) {
runs := []goagent.RunSummary{{RunID: "run-1", Status: "error", Events: 4, LastKind: "tool", LastError: "boom", TraceID: "1234567890abcdef", Checkpoint: "failed", Stage: "ask"}}
runs := []goagent.RunSummary{{RunID: "run-1", Status: "auth", Events: 4, LastKind: "model", LastError: "invalid API key", LastErrorKind: "auth", TraceID: "1234567890abcdef", Checkpoint: "failed", Stage: "ask", Spent: 7}}
var out bytes.Buffer
if err := writeAgentInspection(&out, "support", runs, false); err != nil {
t.Fatal(err)
}
got := out.String()
for _, want := range []string{"Agent \"support\" runs", "run-1", "status=error", "events=4", "last=tool", "checkpoint=failed", "stage=ask", `error="boom"`, "trace=1234567890ab", `micro agent history support run-1`, `micro.AgentResume(ctx, agent, "run-1")`, `micro.ResumeStreamAsk(ctx, agent, "run-1")`} {
for _, want := range []string{"Agent \"support\" runs", "run-1", "status=auth", "events=4", "last=model", "checkpoint=failed", "stage=ask", "error_kind=auth", `error="invalid API key"`, "trace=1234567890ab", "spent=7"} {
if !strings.Contains(got, want) {
t.Fatalf("output missing %q:\n%s", want, got)
}
@@ -31,7 +31,7 @@ func TestWriteAgentInspectionIncludesInputResumeBreadcrumb(t *testing.T) {
t.Fatal(err)
}
got := out.String()
for _, want := range []string{"checkpoint=paused", "stage=input-required", `micro agent history support run-input`, `micro.AgentResumeInput(ctx, agent, "run-input", input)`} {
for _, want := range []string{"checkpoint=paused", "stage=input-required", `micro agent history support run-input`, `micro agent resume-input support run-input --input <text>`} {
if !strings.Contains(got, want) {
t.Fatalf("output missing %q:\n%s", want, got)
}
+2 -2
View File
@@ -12,12 +12,12 @@ import (
_ "go-micro.dev/v6/cmd/micro/cli/build"
_ "go-micro.dev/v6/cmd/micro/cli/deploy"
_ "go-micro.dev/v6/cmd/micro/flow"
"go-micro.dev/v6/cmd/micro/gateway"
_ "go-micro.dev/v6/cmd/micro/inspect"
_ "go-micro.dev/v6/cmd/micro/loop"
_ "go-micro.dev/v6/cmd/micro/mcp"
_ "go-micro.dev/v6/cmd/micro/resource"
_ "go-micro.dev/v6/cmd/micro/run"
"go-micro.dev/v6/cmd/micro/server"
)
//go:embed web/styles.css web/main.js web/templates/*
@@ -26,7 +26,7 @@ var webFS embed.FS
var version = "5.0.0-dev"
func init() {
server.HTML = webFS
gateway.HTML = webFS
}
func main() {
+158 -43
View File
@@ -7,6 +7,7 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
@@ -22,9 +23,10 @@ import (
clt "go-micro.dev/v6/client"
"go-micro.dev/v6/cmd"
"go-micro.dev/v6/cmd/micro/cli/generate"
"go-micro.dev/v6/cmd/micro/gateway"
"go-micro.dev/v6/cmd/micro/run/config"
"go-micro.dev/v6/cmd/micro/run/watcher"
"go-micro.dev/v6/cmd/micro/server"
"go-micro.dev/v6/gateway/mcp"
"go-micro.dev/v6/registry"
_ "go-micro.dev/v6/ai/anthropic"
@@ -69,7 +71,20 @@ type serviceProcess struct {
running bool
}
func (s *serviceProcess) start(logDir string) error {
// build compiles the service to the given output path. It is slow (invokes the
// Go toolchain) and must be called WITHOUT holding s.mu, so the running process
// keeps serving while a rebuild is in flight.
func (s *serviceProcess) build(out string) error {
buildCmd := exec.Command("go", "build", "-o", out, ".")
buildCmd.Dir = s.dir
if buildOut, err := buildCmd.CombinedOutput(); err != nil {
return fmt.Errorf("build failed: %s\n%s", err, string(buildOut))
}
return nil
}
// launch starts the already-built binary at s.binPath and streams its output.
func (s *serviceProcess) launch(logDir string) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -77,14 +92,6 @@ func (s *serviceProcess) start(logDir string) error {
return nil
}
// Build
buildCmd := exec.Command("go", "build", "-o", s.binPath, ".")
buildCmd.Dir = s.dir
buildOut, buildErr := buildCmd.CombinedOutput()
if buildErr != nil {
return fmt.Errorf("build failed: %s\n%s", buildErr, string(buildOut))
}
// Open log file
logFile, err := os.OpenFile(s.logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
@@ -101,10 +108,13 @@ func (s *serviceProcess) start(logDir string) error {
s.cmd.Stdout = pw
s.cmd.Stderr = pw
// Stream output
// Stream output. The larger buffer keeps long lines (JSON logs, stack
// traces) from overflowing the scanner and silently dropping a service's
// logs from that point on.
go func(name string, color string, pr *io.PipeReader, logFile *os.File) {
defer logFile.Close()
scanner := bufio.NewScanner(pr)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for scanner.Scan() {
line := scanner.Text()
fmt.Printf("%s[%s]%s %s\n", color, name, colorReset, line)
@@ -127,6 +137,14 @@ func (s *serviceProcess) start(logDir string) error {
return nil
}
// start builds the service and launches it (initial start).
func (s *serviceProcess) start(logDir string) error {
if err := s.build(s.binPath); err != nil {
return err
}
return s.launch(logDir)
}
func (s *serviceProcess) stop() {
s.mu.Lock()
defer s.mu.Unlock()
@@ -161,9 +179,21 @@ func (s *serviceProcess) stop() {
s.running = false
}
func (s *serviceProcess) restart(logDir string) error {
// reload rebuilds the service and swaps in the new binary ONLY if the build
// succeeds. A failing build (a typo, a broken import) leaves the running
// process untouched, so a compile error never takes the service offline — the
// caller reports the error and the previous version keeps serving.
func (s *serviceProcess) reload(logDir string) error {
newBin := s.binPath + ".new"
if err := s.build(newBin); err != nil {
_ = os.Remove(newBin)
return err
}
s.stop()
return s.start(logDir)
if err := os.Rename(newBin, s.binPath); err != nil {
return fmt.Errorf("swap binary: %w", err)
}
return s.launch(logDir)
}
// waitForHealth waits for a service's health endpoint to respond
@@ -338,27 +368,50 @@ func Run(c *cli.Context) error {
}
// Start gateway unless disabled
var gw *server.Gateway
var gw *gateway.Gateway
var mcpServer *mcp.Server
gatewayAddr := c.String("address")
if gatewayAddr == "" {
gatewayAddr = ":8080"
gatewayAddr = "127.0.0.1:8080"
}
// Auth follows the socket. micro run binds loopback by default, so auth is
// off for the local dev loop — no login to call your own tools — while
// scoped/paid tools still require the machine token.
authEnabled, authToken := gateway.ResolveAuth(c, gatewayAddr)
if !c.Bool("no-gateway") {
var err error
mcpAddr := c.String("mcp-address")
gw, err = server.StartGateway(server.GatewayOptions{
gw, err = gateway.StartGateway(gateway.GatewayOptions{
Address: gatewayAddr,
AuthEnabled: true, // Auth enabled with default admin/micro user
AuthEnabled: authEnabled,
Context: context.Background(),
MCPEnabled: mcpAddr != "",
MCPAddress: mcpAddr,
})
if err != nil {
return fmt.Errorf("failed to start gateway: %w", err)
}
}
// The MCP gateway runs independently of the HTTP API gateway. When
// --mcp-address is set, start it explicitly with the production controls
// (rate limiting, scopes, auth, x402 payments) instead of letting the API
// gateway spawn a bare listener.
if mcpAddr := c.String("mcp-address"); mcpAddr != "" {
mcpOpts, err := buildRunMCPOptions(c, mcpAddr)
if err != nil {
return fmt.Errorf("failed to configure MCP gateway: %w", err)
}
mcpServer, err = mcp.NewServer(mcpOpts)
if err != nil {
return fmt.Errorf("failed to start MCP gateway: %w", err)
}
go func() {
if err := mcpServer.Serve(); err != nil {
fmt.Fprintf(os.Stderr, "[mcp] gateway error: %v\n", err)
}
}()
}
// Start services
for _, svc := range services {
if err := svc.start(logsDir); err != nil {
@@ -375,12 +428,22 @@ func Run(c *cli.Context) error {
}
// Print startup banner
printBanner(services, gw, !c.Bool("no-watch"), c.String("mcp-address"))
printBanner(services, gw, !c.Bool("no-watch"), c.String("mcp-address"), authEnabled, authToken)
// Setup signal handling
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
// shutdown is closed once when teardown begins. Background goroutines watch
// it instead of sigCh — a signal is delivered to only one channel receiver,
// so sharing sigCh would let a goroutine steal the interrupt and hang the
// main wait below.
shutdown := make(chan struct{})
// svcMu guards services/servicesByDir, which the new-service scanner mutates
// concurrently with the shutdown loop.
var svcMu sync.Mutex
// Watch mode
watchEnabled := !c.Bool("no-watch")
var watch *watcher.Watcher
@@ -396,11 +459,17 @@ func Run(c *cli.Context) error {
go func() {
for event := range watch.Events() {
if svc, ok := servicesByDir[event.Dir]; ok {
fmt.Printf("%s[%s]%s rebuilding...\n", svc.color, svc.name, colorReset)
if err := svc.restart(logsDir); err != nil {
fmt.Fprintf(os.Stderr, "%s[%s]%s restart failed: %v\n", svc.color, svc.name, colorReset, err)
}
svcMu.Lock()
svc, ok := servicesByDir[event.Dir]
svcMu.Unlock()
if !ok {
continue
}
fmt.Printf("%s[%s]%s rebuilding...\n", svc.color, svc.name, colorReset)
if err := svc.reload(logsDir); err != nil {
// Build failed — the previous version is still serving.
fmt.Fprintf(os.Stderr, "%s[%s]%s build failed, keeping previous version running:\n%v\n",
svc.color, svc.name, colorReset, err)
}
}
}()
@@ -411,13 +480,17 @@ func Run(c *cli.Context) error {
defer ticker.Stop()
for {
select {
case <-sigCh:
case <-shutdown:
return
case <-ticker.C:
svcMu.Lock()
newSvcs := discoverNewServices(absDir, servicesByDir, binDir, runDir, logsDir, envVars, len(services))
for _, sp := range newSvcs {
services = append(services, sp)
servicesByDir[sp.dir] = sp
}
svcMu.Unlock()
for _, sp := range newSvcs {
watch.AddDir(sp.dir)
if err := sp.start(logsDir); err != nil {
fmt.Fprintf(os.Stderr, "[%s] %v\n", sp.name, err)
@@ -438,6 +511,8 @@ func Run(c *cli.Context) error {
}
fmt.Println("\nShutting down...")
close(shutdown)
if watch != nil {
watch.Stop()
}
@@ -446,14 +521,36 @@ func Run(c *cli.Context) error {
_ = gw.Stop()
}
// Stop services in reverse order
for i := len(services) - 1; i >= 0; i-- {
services[i].stop()
if mcpServer != nil {
_ = mcpServer.Stop()
}
// Stop services in reverse order. Snapshot under the lock — the scanner
// goroutine may still be appending as teardown begins.
svcMu.Lock()
all := make([]*serviceProcess, len(services))
copy(all, services)
svcMu.Unlock()
for i := len(all) - 1; i >= 0; i-- {
all[i].stop()
}
return nil
}
// buildRunMCPOptions assembles MCP gateway options for `micro run`. The dev
// command keeps a minimal setup (registry, context, logger) — the same bare
// listener the API gateway used to spawn — while production controls (rate
// limiting, scopes, x402) stay on the standalone `micro gateway` command.
func buildRunMCPOptions(c *cli.Context, addr string) (mcp.Options, error) {
return mcp.Options{
Registry: registry.DefaultRegistry,
Address: addr,
Context: context.Background(),
Logger: log.Default(),
}, nil
}
func discoverNewServices(baseDir string, known map[string]*serviceProcess, binDir, runDir, logsDir string, envVars []string, colorOffset int) []*serviceProcess {
var newSvcs []*serviceProcess
entries, err := os.ReadDir(baseDir)
@@ -489,23 +586,23 @@ func discoverNewServices(baseDir string, known map[string]*serviceProcess, binDi
return newSvcs
}
func printBanner(services []*serviceProcess, gw *server.Gateway, watching bool, mcpAddr string) {
func printBanner(services []*serviceProcess, gw *gateway.Gateway, watching bool, mcpAddr string, authEnabled bool, authToken string) {
fmt.Println()
fmt.Println(" \033[1mMicro\033[0m")
fmt.Println()
if gw != nil {
fmt.Printf(" Dashboard \033[36mhttp://localhost%s\033[0m\n", gw.Addr())
fmt.Printf(" API \033[36mhttp://localhost%s/api/{service}/{method}\033[0m\n", gw.Addr())
fmt.Printf(" Agent \033[36mhttp://localhost%s/agent\033[0m\n", gw.Addr())
fmt.Printf(" Dashboard \033[36mhttp://%s\033[0m\n", gw.Addr())
fmt.Printf(" API \033[36mhttp://%s/api/{service}/{method}\033[0m\n", gw.Addr())
fmt.Printf(" Agent \033[36mhttp://%s/agent\033[0m\n", gw.Addr())
// MCP tools are served on the gateway by default — every endpoint is an
// AI-callable tool, so surface it rather than hiding it behind a flag.
fmt.Printf(" MCP Tools \033[36mhttp://localhost%s/mcp/tools\033[0m\n", gw.Addr())
fmt.Printf(" Health \033[36mhttp://localhost%s/health\033[0m\n", gw.Addr())
fmt.Printf(" MCP Tools \033[36mhttp://%s/mcp/tools\033[0m\n", gw.Addr())
fmt.Printf(" Health \033[36mhttp://%s/health\033[0m\n", gw.Addr())
if mcpAddr != "" {
// Optional standalone MCP protocol server (e.g. for MCP clients).
fmt.Printf(" MCP Server \033[36mhttp://localhost%s\033[0m (full MCP protocol)\n", mcpAddr)
fmt.Printf(" WebSocket \033[36mws://localhost%s/mcp/ws\033[0m\n", mcpAddr)
fmt.Printf(" MCP Server \033[36mhttp://%s\033[0m (full MCP protocol)\n", mcpAddr)
fmt.Printf(" WebSocket \033[36mws://%s/mcp/ws\033[0m\n", mcpAddr)
}
}
@@ -541,7 +638,19 @@ func printBanner(services []*serviceProcess, gw *server.Gateway, watching bool,
}
fmt.Println()
fmt.Println(" Auth: \033[32menabled\033[0m (admin / micro)")
if authEnabled {
fmt.Println(" Auth: \033[32mon\033[0m (address is exposed)")
if authToken != "" {
fmt.Printf(" Token: \033[36m%s\033[0m \033[2m(shown once — use as Authorization: Bearer)\033[0m\n", authToken)
} else {
fmt.Println(" Token: \033[2mset via MICRO_AUTH_TOKEN\033[0m")
}
} else {
fmt.Println(" Auth: \033[2moff (loopback — no login needed)\033[0m")
if authToken != "" {
fmt.Printf(" \033[2mScoped/paid tools need a token: %s\033[0m\n", authToken)
}
}
if watching {
fmt.Println(" \033[33mWatching for changes...\033[0m")
@@ -688,6 +797,12 @@ Starts an HTTP gateway on :8080 providing:
With a micro.mu or micro.json config file, services start in dependency order.
Without config, all main.go files are discovered and run.
micro run is a local development tool — it builds and supervises service
processes with hot reload. It is not a production runtime: there is no daemon,
and processes stop when micro run exits. For production, build each service
(go build) and run it under a process manager or scheduler — systemd,
Docker/Compose, or Kubernetes (see deploy/kubernetes).
Examples:
micro run # Run with gateway on :8080
micro run --address :3000 # Gateway on custom port
@@ -697,12 +812,12 @@ Examples:
micro run --mcp-address :3000 # Enable MCP protocol gateway
micro run --prompt "an order system for dropshipping" # Generate and run`,
Action: Run,
Flags: []cli.Flag{
Flags: append([]cli.Flag{
&cli.StringFlag{
Name: "address",
Aliases: []string{"a"},
Usage: "Gateway address (default :8080)",
Value: ":8080",
Usage: "Gateway address (default 127.0.0.1:8080, loopback). A non-loopback address turns auth on.",
Value: "127.0.0.1:8080",
},
&cli.BoolFlag{
Name: "no-gateway",
@@ -743,7 +858,7 @@ Examples:
Usage: "API key for --prompt (or set ANTHROPIC_API_KEY, OPENAI_API_KEY, etc.)",
EnvVars: []string{"MICRO_AI_API_KEY"},
},
},
}, gateway.AuthFlags()...),
})
}
+36
View File
@@ -0,0 +1,36 @@
# Kubernetes deployment foundation (alpha)
This package is the first opt-in Kubernetes foundation for the Go Micro lifecycle:
`Service`, `Agent`, and `Flow` resources. It is intentionally experimental and
additive. Nothing in the Go Micro runtime installs these resources or changes
production defaults.
## What is included
- Alpha CRD manifests in `config/crd/` for `agents.micro.dev`,
`services.micro.dev`, and `flows.micro.dev`.
- A small dependency-free mapper that turns a desired Go Micro resource into the
Kubernetes `Deployment` shape an operator reconciliation loop will own.
- A dependency-free `Reconcile(desired, observed)` core that decides the one
action needed to converge (create / update / noop) and the `Ready`/`Error`
status conditions — no controller-runtime, no client-go, fully unit-testable.
A future operator binary supplies the observed state and applies the action;
only that adapter needs the Kubernetes client.
- Unit tests that validate the structural CRD fragments, the Agent-to-Deployment
mapping, and the reconcile decision/conditions.
## Local validation
```sh
go test ./deploy/kubernetes
```
If you have a Kubernetes cluster and `kubectl` available, you can also perform a
server-side dry run of the CRDs:
```sh
kubectl apply --dry-run=server -f deploy/kubernetes/config/crd/
```
The manifests are `v1alpha1`; expect the API shape to evolve before this becomes
a production operator.
+37
View File
@@ -0,0 +1,37 @@
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: agents.micro.dev
spec:
group: micro.dev
scope: Namespaced
names:
plural: agents
singular: agent
kind: Agent
shortNames: [magent]
versions:
- name: v1alpha1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
required: [spec]
properties:
spec:
type: object
required: [image]
properties:
image: {type: string, minLength: 1}
command:
type: array
items: {type: string}
args:
type: array
items: {type: string}
replicas: {type: integer, minimum: 0}
registry: {type: string}
env:
type: object
additionalProperties: {type: string}
+37
View File
@@ -0,0 +1,37 @@
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: flows.micro.dev
spec:
group: micro.dev
scope: Namespaced
names:
plural: flows
singular: flow
kind: Flow
shortNames: [mflow]
versions:
- name: v1alpha1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
required: [spec]
properties:
spec:
type: object
required: [image]
properties:
image: {type: string, minLength: 1}
command:
type: array
items: {type: string}
args:
type: array
items: {type: string}
replicas: {type: integer, minimum: 0}
registry: {type: string}
env:
type: object
additionalProperties: {type: string}
+37
View File
@@ -0,0 +1,37 @@
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: services.micro.dev
spec:
group: micro.dev
scope: Namespaced
names:
plural: services
singular: service
kind: Service
shortNames: [mservice]
versions:
- name: v1alpha1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
required: [spec]
properties:
spec:
type: object
required: [image]
properties:
image: {type: string, minLength: 1}
command:
type: array
items: {type: string}
args:
type: array
items: {type: string}
replicas: {type: integer, minimum: 0}
registry: {type: string}
env:
type: object
additionalProperties: {type: string}
+8
View File
@@ -0,0 +1,8 @@
// Package kubernetes contains the experimental Kubernetes deployment foundation
// for Go Micro services, agents, and flows.
//
// The package is intentionally small and additive: it exposes alpha custom
// resource manifests and a dry-run mapper that turns a resource spec into the
// Deployment shape an operator would reconcile. It does not install an operator
// or change any runtime defaults.
package kubernetes
+87
View File
@@ -0,0 +1,87 @@
package kubernetes
import (
"strings"
"testing"
)
func TestCRDManifestsAreStructural(t *testing.T) {
for _, kind := range []Kind{KindAgent, KindService, KindFlow} {
manifest := CRDManifests[kind]
if manifest == "" {
t.Fatalf("missing manifest for %s", kind)
}
checks := []string{
"apiVersion: apiextensions.k8s.io/v1",
"kind: CustomResourceDefinition",
"group: micro.dev",
"kind: " + string(kind),
"name: v1alpha1",
"served: true",
"storage: true",
"openAPIV3Schema:",
"type: object",
"required: [image]",
}
for _, check := range checks {
if !strings.Contains(manifest, check) {
t.Fatalf("%s manifest missing %q:\n%s", kind, check, manifest)
}
}
}
}
func TestMapDeploymentForAgent(t *testing.T) {
deployment, err := MapDeployment(Resource{
Kind: KindAgent,
Name: "support-agent",
Namespace: "agents",
Spec: WorkloadSpec{
Image: "ghcr.io/acme/support-agent:v1",
Replicas: 2,
Registry: "kubernetes",
Environment: map[string]string{
"MODEL": "gpt-5.5",
},
},
})
if err != nil {
t.Fatalf("MapDeployment returned error: %v", err)
}
if deployment.Name != "support-agent" || deployment.Namespace != "agents" {
t.Fatalf("unexpected identity: %+v", deployment)
}
if deployment.Replicas != 2 {
t.Fatalf("replicas = %d, want 2", deployment.Replicas)
}
if got := deployment.Labels["micro.dev/kind"]; got != "agent" {
t.Fatalf("micro.dev/kind label = %q, want agent", got)
}
container := deployment.Pod.Container
if container.Image != "ghcr.io/acme/support-agent:v1" {
t.Fatalf("image = %q", container.Image)
}
if got := container.Environment["MICRO_REGISTRY"]; got != "kubernetes" {
t.Fatalf("MICRO_REGISTRY = %q, want kubernetes", got)
}
if got := container.Environment["MODEL"]; got != "gpt-5.5" {
t.Fatalf("MODEL = %q, want gpt-5.5", got)
}
}
func TestMapDeploymentDefaultsAndValidation(t *testing.T) {
deployment, err := MapDeployment(Resource{Kind: KindService, Name: "api", Spec: WorkloadSpec{Image: "api:latest"}})
if err != nil {
t.Fatalf("MapDeployment returned error: %v", err)
}
if deployment.Namespace != "default" || deployment.Replicas != 1 {
t.Fatalf("defaults = namespace %q replicas %d", deployment.Namespace, deployment.Replicas)
}
if _, err := MapDeployment(Resource{Kind: KindFlow, Name: "ingest"}); err == nil {
t.Fatal("MapDeployment without image succeeded")
}
if _, err := MapDeployment(Resource{Kind: "Job", Name: "job", Spec: WorkloadSpec{Image: "job:latest"}}); err == nil {
t.Fatal("MapDeployment with unsupported kind succeeded")
}
}
+32
View File
@@ -0,0 +1,32 @@
package kubernetes
import (
"embed"
"fmt"
)
// crdFS holds the canonical CRD manifests. They live as real YAML under
// config/crd/ so they can be applied directly (`kubectl apply -f
// deploy/kubernetes/config/crd/`) and are embedded here so the Go API serves
// the exact same bytes — one source of truth, no drift.
//
//go:embed config/crd/agent.yaml config/crd/service.yaml config/crd/flow.yaml
var crdFS embed.FS
// CRDManifests contains the alpha CRDs for Go Micro lifecycle resources, loaded
// from the embedded config/crd/ YAML.
var CRDManifests = map[Kind]string{
KindAgent: mustCRD("agent"),
KindService: mustCRD("service"),
KindFlow: mustCRD("flow"),
}
// mustCRD reads an embedded CRD manifest. The files are embedded at compile
// time, so a read error means a build/packaging bug, not a runtime condition.
func mustCRD(name string) string {
b, err := crdFS.ReadFile("config/crd/" + name + ".yaml")
if err != nil {
panic(fmt.Sprintf("kubernetes: embedded CRD %q missing: %v", name, err))
}
return string(b)
}
+105
View File
@@ -0,0 +1,105 @@
package kubernetes
import (
"fmt"
"reflect"
)
// Reconcile is the pure decision core an operator's reconcile loop runs: given
// a desired resource and the currently observed cluster state, it computes the
// one action needed to converge (create / update / nothing) plus the status
// conditions to publish. It does not talk to a cluster — no controller-runtime,
// no client-go — so the whole convergence decision is unit-testable. An adapter
// binary supplies Observed from the live cluster and applies the returned
// Action; that adapter is the only piece that needs the Kubernetes client.
// ActionType is the change a reconcile wants applied.
type ActionType string
const (
// ActionCreate means the workload does not exist yet and should be created.
ActionCreate ActionType = "create"
// ActionUpdate means the workload exists but drifts from desired.
ActionUpdate ActionType = "update"
// ActionNoop means the workload already matches desired.
ActionNoop ActionType = "noop"
)
// Action is the change Reconcile decided on, carrying the desired Deployment.
type Action struct {
Type ActionType
Deployment Deployment
}
// Observed is the current cluster state Reconcile compares against. The adapter
// fills it from the live cluster; a nil Deployment means "not created yet".
type Observed struct {
// Deployment is the workload as it currently exists, or nil if absent.
Deployment *Deployment
// ReadyReplicas is how many pods are ready, from the live Deployment status.
ReadyReplicas int32
}
// Condition is a status condition to publish on the resource — the ready/error
// signal for the inner-loop and deploy story. It mirrors the Kubernetes
// condition shape without importing the API types.
type Condition struct {
Type string `json:"type"` // "Ready" | "Error"
Status string `json:"status"` // "True" | "False" | "Unknown"
Reason string `json:"reason"`
Message string `json:"message,omitempty"`
}
// Reconcile computes the action to bring observed toward desired, plus the
// status conditions. A spec that fails to map returns an Error condition and
// the error (no action).
func Reconcile(desired Resource, observed Observed) (Action, []Condition, error) {
want, err := MapDeployment(desired)
if err != nil {
return Action{}, []Condition{{
Type: "Error", Status: "True", Reason: "InvalidSpec", Message: err.Error(),
}}, err
}
var action Action
switch {
case observed.Deployment == nil:
action = Action{Type: ActionCreate, Deployment: want}
case deploymentDiffers(*observed.Deployment, want):
action = Action{Type: ActionUpdate, Deployment: want}
default:
action = Action{Type: ActionNoop, Deployment: want}
}
return action, conditions(want, observed), nil
}
// conditions derives the Ready condition from observed state against desired.
func conditions(want Deployment, observed Observed) []Condition {
switch {
case observed.Deployment == nil:
return []Condition{{
Type: "Ready", Status: "False", Reason: "Creating",
Message: "workload not yet created",
}}
case observed.ReadyReplicas < want.Replicas:
return []Condition{{
Type: "Ready", Status: "False", Reason: "Progressing",
Message: fmt.Sprintf("%d/%d replicas ready", observed.ReadyReplicas, want.Replicas),
}}
default:
return []Condition{{
Type: "Ready", Status: "True", Reason: "Available",
Message: fmt.Sprintf("%d/%d replicas ready", observed.ReadyReplicas, want.Replicas),
}}
}
}
// deploymentDiffers reports whether the observed deployment drifts from desired
// on the fields this operator manages (replicas, container, labels). Fields the
// cluster owns (status, cluster-assigned metadata) are intentionally ignored.
func deploymentDiffers(current, want Deployment) bool {
return current.Replicas != want.Replicas ||
!reflect.DeepEqual(current.Pod.Container, want.Pod.Container) ||
!reflect.DeepEqual(current.Labels, want.Labels)
}
+88
View File
@@ -0,0 +1,88 @@
package kubernetes
import "testing"
func agentResource() Resource {
return Resource{
Kind: KindAgent,
Name: "support",
Namespace: "agents",
Spec: WorkloadSpec{Image: "example/support:v1", Replicas: 2, Registry: "kubernetes"},
}
}
func TestReconcileCreatesWhenAbsent(t *testing.T) {
action, conds, err := Reconcile(agentResource(), Observed{Deployment: nil})
if err != nil {
t.Fatalf("Reconcile: %v", err)
}
if action.Type != ActionCreate {
t.Fatalf("action = %q, want create", action.Type)
}
if action.Deployment.Name != "support" || action.Deployment.Replicas != 2 {
t.Fatalf("desired deployment = %+v", action.Deployment)
}
if ready := findCondition(conds, "Ready"); ready == nil || ready.Status != "False" || ready.Reason != "Creating" {
t.Fatalf("ready condition = %+v, want False/Creating", ready)
}
}
func TestReconcileNoopWhenMatchedAndReady(t *testing.T) {
want, _ := MapDeployment(agentResource())
action, conds, err := Reconcile(agentResource(), Observed{Deployment: &want, ReadyReplicas: 2})
if err != nil {
t.Fatalf("Reconcile: %v", err)
}
if action.Type != ActionNoop {
t.Fatalf("action = %q, want noop", action.Type)
}
if ready := findCondition(conds, "Ready"); ready == nil || ready.Status != "True" || ready.Reason != "Available" {
t.Fatalf("ready condition = %+v, want True/Available", ready)
}
}
func TestReconcileUpdatesOnDrift(t *testing.T) {
current, _ := MapDeployment(agentResource())
current.Pod.Container.Image = "example/support:v0" // stale image → drift
action, _, err := Reconcile(agentResource(), Observed{Deployment: &current, ReadyReplicas: 2})
if err != nil {
t.Fatalf("Reconcile: %v", err)
}
if action.Type != ActionUpdate {
t.Fatalf("action = %q, want update", action.Type)
}
if action.Deployment.Pod.Container.Image != "example/support:v1" {
t.Fatalf("update should carry the desired image, got %q", action.Deployment.Pod.Container.Image)
}
}
func TestReconcileProgressingWhenUnderReplicated(t *testing.T) {
want, _ := MapDeployment(agentResource())
_, conds, err := Reconcile(agentResource(), Observed{Deployment: &want, ReadyReplicas: 1})
if err != nil {
t.Fatalf("Reconcile: %v", err)
}
if ready := findCondition(conds, "Ready"); ready == nil || ready.Status != "False" || ready.Reason != "Progressing" {
t.Fatalf("ready condition = %+v, want False/Progressing", ready)
}
}
func TestReconcileErrorOnInvalidSpec(t *testing.T) {
// Missing image → MapDeployment fails → Error condition, no action.
_, conds, err := Reconcile(Resource{Kind: KindService, Name: "api"}, Observed{})
if err == nil {
t.Fatal("Reconcile should error on an invalid spec")
}
if e := findCondition(conds, "Error"); e == nil || e.Status != "True" || e.Reason != "InvalidSpec" {
t.Fatalf("error condition = %+v, want True/InvalidSpec", e)
}
}
func findCondition(conds []Condition, typ string) *Condition {
for i := range conds {
if conds[i].Type == typ {
return &conds[i]
}
}
return nil
}
+138
View File
@@ -0,0 +1,138 @@
package kubernetes
import (
"fmt"
"sort"
"strings"
)
const (
// Group is the API group for the alpha Go Micro Kubernetes resources.
Group = "micro.dev"
// Version is the current alpha API version for the CRDs in this package.
Version = "v1alpha1"
)
// Kind identifies a Go Micro lifecycle resource that can be reconciled toward a
// Kubernetes Deployment.
type Kind string
const (
KindAgent Kind = "Agent"
KindService Kind = "Service"
KindFlow Kind = "Flow"
)
// WorkloadSpec is the common alpha spec shared by Agent, Service, and Flow CRDs.
type WorkloadSpec struct {
Image string `json:"image"`
Command []string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Replicas int32 `json:"replicas,omitempty"`
Registry string `json:"registry,omitempty"`
Environment map[string]string `json:"env,omitempty"`
}
// Resource is the minimal desired state for a Go Micro lifecycle resource.
type Resource struct {
Kind Kind
Name string
Namespace string
Spec WorkloadSpec
}
// Deployment is a small, dependency-free representation of the Kubernetes
// Deployment fields the alpha reconciler skeleton owns.
type Deployment struct {
Name string
Namespace string
Labels map[string]string
Replicas int32
Pod PodTemplate
}
// PodTemplate describes the pod fields emitted by MapDeployment.
type PodTemplate struct {
Labels map[string]string
Container Container
}
// Container describes the single Go Micro workload container.
type Container struct {
Name string
Image string
Command []string
Args []string
Environment map[string]string
}
// MapDeployment maps a Go Micro alpha resource to the Deployment shape an
// operator reconciliation loop would apply.
func MapDeployment(resource Resource) (Deployment, error) {
if resource.Kind != KindAgent && resource.Kind != KindService && resource.Kind != KindFlow {
return Deployment{}, fmt.Errorf("unsupported kind %q", resource.Kind)
}
name := strings.TrimSpace(resource.Name)
if name == "" {
return Deployment{}, fmt.Errorf("name is required")
}
image := strings.TrimSpace(resource.Spec.Image)
if image == "" {
return Deployment{}, fmt.Errorf("spec.image is required")
}
namespace := strings.TrimSpace(resource.Namespace)
if namespace == "" {
namespace = "default"
}
replicas := resource.Spec.Replicas
if replicas == 0 {
replicas = 1
}
labels := map[string]string{
"app.kubernetes.io/name": name,
"app.kubernetes.io/managed-by": "go-micro",
"micro.dev/kind": strings.ToLower(string(resource.Kind)),
}
env := copyMap(resource.Spec.Environment)
if resource.Spec.Registry != "" {
env["MICRO_REGISTRY"] = resource.Spec.Registry
}
return Deployment{
Name: name,
Namespace: namespace,
Labels: copyMap(labels),
Replicas: replicas,
Pod: PodTemplate{
Labels: copyMap(labels),
Container: Container{
Name: name,
Image: image,
Command: append([]string(nil), resource.Spec.Command...),
Args: append([]string(nil), resource.Spec.Args...),
Environment: env,
},
},
}, nil
}
// EnvironmentKeys returns stable environment variable keys from a mapped
// container. It is useful for deterministic validation and rendering.
func (c Container) EnvironmentKeys() []string {
keys := make([]string, 0, len(c.Environment))
for key := range c.Environment {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
func copyMap(in map[string]string) map[string]string {
out := make(map[string]string, len(in))
for k, v := range in {
out[k] = v
}
return out
}
+6 -2
View File
@@ -12,7 +12,9 @@ provider-free unless the example README says otherwise.
| Prove the maintained 0→hero path | [`support`](./support/) | `go run ./examples/support` and `go test ./examples/support` | [`zero-to-hero` guide](../internal/website/docs/guides/zero-to-hero.md) |
| See planning and delegation | [`agent-plan-delegate`](./agent-plan-delegate/) | `go run ./examples/agent-plan-delegate` | [`plan-delegate` guide](../internal/website/docs/guides/plan-delegate.md) |
| Expose services through MCP | [`mcp/hello`](./mcp/hello/) | follow [`mcp`](./mcp/) setup | [`mcp/crud`](./mcp/crud/) and [`mcp/workflow`](./mcp/workflow/) |
| Try A2A or gRPC interop next | [`agent-demo`](./agent-demo/) plus gateway docs | run the example, then use the gateway docs | [`grpc-interop`](./grpc-interop/) |
| Try a paid tool with x402 | [`agent-x402-buyer`](./agent-x402-buyer/) | `go run ./examples/agent-x402-buyer` | [`Payments (x402)` guide](../internal/website/docs/guides/x402-payments.md) |
| Try A2A or gRPC interop next | [`agent-demo`](./agent-demo/) plus gateway docs | run the example, then use the gateway docs | [`grpc`](./grpc/) and [`grpc-interop`](./grpc-interop/) |
| Call a service with grpcurl | [`grpc`](./grpc/) | `grpcurl -plaintext localhost:8080 list` then `grpcurl -plaintext -d '{"name":"World"}' localhost:8080 helloworld.Say.Hello` | [`grpc-interop`](./grpc-interop/) |
| Add workflow durability | [`flow-durable`](./flow-durable/) | `go run ./examples/flow-durable` | [`flow-loop`](./flow-loop/) |
## Recommended adoption path
@@ -28,7 +30,9 @@ provider-free unless the example README says otherwise.
4. **Interop next:** use [`mcp/hello`](./mcp/hello/), [`mcp/crud`](./mcp/crud/),
and [`mcp/workflow`](./mcp/workflow/) when you are ready to expose tools to
external AI clients.
5. **Workflow depth:** use [`flow-durable`](./flow-durable/) once the agent path
5. **Paid tools:** run [`agent-x402-buyer`](./agent-x402-buyer/) to see an
agent pay a local x402-protected tool with a mock facilitator and budget.
6. **Workflow depth:** use [`flow-durable`](./flow-durable/) once the agent path
needs checkpointed, resumable deterministic work.
## CLI wayfinding
+4 -1
View File
@@ -140,13 +140,16 @@ Authentication and authorization example.
### [graceful-stop](./graceful-stop/)
Graceful shutdown behavior for long-running services.
### [grpc](./grpc/)
go-micro v6 as a standard gRPC-compatible server: reflection enabled, callable
by grpcurl and any standard gRPC client.
### [grpc-interop](./grpc-interop/)
gRPC interoperability example.
## Coming Soon
- **pubsub-events** - Event-driven architecture with NATS
- **grpc-integration** - Using go-micro with gRPC
## Prerequisites
+1 -1
View File
@@ -60,4 +60,4 @@ Try these with Claude Code or any MCP client:
4. **Auth scopes** — Read and write operations have separate scopes
5. **`WithMCP` one-liner** — MCP gateway starts with a single option
See the [blog post](/blog/4) for a detailed walkthrough.
See the [blog post](https://go-micro.dev/blog/2026/03/04/agents-meet-microservices-a-hands-on-demo.html) for a detailed walkthrough.
+24
View File
@@ -0,0 +1,24 @@
# Agent x402 buyer
This example shows an agent paying for a paid HTTP tool with x402 without using
live funds or a live chain.
It starts a local paid endpoint guarded by `wrapper/x402` seller middleware and a
mock facilitator. A deterministic mock-model agent calls that endpoint as a tool,
receives the HTTP 402 challenge, pays with `AgentPayer`, stays inside
`AgentBudget`, retries the request, and prints the spend recorded for the run.
```bash
go run ./examples/agent-x402-buyer
```
Expected output includes:
- the paid tool response,
- one facilitator verify and settle call, and
- `run spend: 7 smallest units (budget 10)`.
The payment token and facilitator are intentionally local development fakes. To
settle real x402 payments, keep the same `AgentPayer` / `AgentBudget` shape but
replace the payer with a wallet-backed implementation and configure the seller
middleware with a hosted or self-run x402 facilitator.
+168
View File
@@ -0,0 +1,168 @@
// Agent x402 buyer — a provider-free example of an agent paying for a paid tool.
//
// Run:
//
// go run ./examples/agent-x402-buyer
//
// It starts a local HTTP tool protected by x402 middleware, then asks a
// deterministic mock-model agent to call that tool. The agent receives the 402
// challenge, uses AgentPayer and AgentBudget to pay within a local mock
// facilitator, retries the request, and prints the run spend.
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
go_micro "go-micro.dev/v6"
"go-micro.dev/v6/agent"
"go-micro.dev/v6/ai"
"go-micro.dev/v6/store"
"go-micro.dev/v6/wrapper/x402"
)
const (
paidToolName = "paid.market_brief"
price = int64(7)
paymentToken = "dev-payment-token"
)
type devFacilitator struct {
verifyCount int
settleCount int
}
func (f *devFacilitator) Verify(ctx context.Context, payment string, req x402.Requirements) (x402.Result, error) {
f.verifyCount++
if payment != paymentToken {
return x402.Result{Valid: false, Reason: "unknown dev payment token"}, nil
}
return x402.Result{Valid: true, Payer: "dev-agent-wallet"}, nil
}
func (f *devFacilitator) Settle(ctx context.Context, payment string, req x402.Requirements) (x402.Result, error) {
f.settleCount++
return x402.Result{Valid: true, Settlement: "dev-settlement-001"}, nil
}
type devPayer struct{}
func (devPayer) Pay(ctx context.Context, req x402.Requirements) (string, error) {
return paymentToken, nil
}
type mockModel struct{ opts ai.Options }
func newMock(opts ...ai.Option) ai.Model {
m := &mockModel{}
_ = m.Init(opts...)
return m
}
func (m *mockModel) Init(opts ...ai.Option) error {
for _, o := range opts {
o(&m.opts)
}
return nil
}
func (m *mockModel) Options() ai.Options { return m.opts }
func (m *mockModel) String() string { return "agent-x402-buyer-mock" }
func (m *mockModel) Stream(context.Context, *ai.Request, ...ai.GenerateOption) (ai.Stream, error) {
return nil, fmt.Errorf("stream not supported by agent-x402-buyer mock")
}
func (m *mockModel) Generate(ctx context.Context, req *ai.Request, _ ...ai.GenerateOption) (*ai.Response, error) {
for _, tool := range req.Tools {
if tool.Name == paidToolName && m.opts.ToolHandler != nil {
out := m.opts.ToolHandler(ctx, ai.ToolCall{ID: "paid-brief", Name: tool.Name, Input: map[string]any{"url": req.Prompt}})
return &ai.Response{Answer: fmt.Sprintf("Paid tool returned: %s", out.Content)}, nil
}
}
return &ai.Response{Answer: "No paid tool was available."}, nil
}
func paidToolServer(fac *devFacilitator) *httptest.Server {
mux := http.NewServeMux()
paid := x402.Middleware(x402.Config{
PayTo: "0xMerchantDevWallet",
Network: "base-sepolia",
Amount: fmt.Sprint(price),
Description: "Local market brief for the x402 buyer example",
Facilitator: fac,
})
mux.Handle("/brief", paid(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"brief": "Mock demand is up 12% after the agent paid the local tool.",
"settlement": w.Header().Get(x402.PaymentResponseHeader),
})
})))
return httptest.NewServer(mux)
}
func run(w io.Writer) error {
ai.Register("agent-x402-buyer-mock", newMock)
fac := &devFacilitator{}
srv := paidToolServer(fac)
defer srv.Close()
st := store.NewMemoryStore()
buyer := agent.New(
agent.Name("x402-buyer"),
agent.Provider("agent-x402-buyer-mock"),
agent.Prompt("Call the paid market brief tool when given its URL."),
agent.WithStore(st),
go_micro.AgentPayer(devPayer{}),
go_micro.AgentBudget(10),
agent.WithTool(paidToolName, "Fetch a paid market brief over HTTP", map[string]any{
"url": map[string]any{"type": "string", "description": "Paid HTTP endpoint to call"},
}, func(ctx context.Context, input map[string]any) (string, error) {
url, _ := input["url"].(string)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}),
)
resp, err := buyer.Ask(context.Background(), srv.URL+"/brief")
if err != nil {
return err
}
events, err := agent.LoadRunEvents(st, "x402-buyer", resp.RunID)
if err != nil {
return err
}
var spent int64
for _, event := range events {
if event.Spent > spent {
spent = event.Spent
}
}
fmt.Fprintln(w, "Agent x402 buyer (provider: mock, funds: local dev token)")
fmt.Fprintln(w, strings.TrimSpace(resp.Reply))
fmt.Fprintf(w, "facilitator verify=%d settle=%d\n", fac.verifyCount, fac.settleCount)
fmt.Fprintf(w, "run spend: %d smallest units (budget 10)\n", spent)
return nil
}
func main() {
if err := run(os.Stdout); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
+1 -1
View File
@@ -379,7 +379,7 @@ if time.Until(token.Expiry) < 5*time.Minute {
## Next Steps
- Read the [Auth Documentation](/docs/auth)
- Read the [Auth Documentation](https://go-micro.dev/docs/auth.html)
- Explore [JWT Auth](/auth/jwt)
- Try [Custom Auth Provider](/examples/auth/custom)
- See [Multi-Tenant Auth](/examples/auth/multi-tenant)
+61
View File
@@ -0,0 +1,61 @@
# gRPC Example
This example shows how to run a go-micro v6 service as a **standard gRPC-compatible
server**: reflection is enabled, so `grpcurl` and other standard gRPC tooling can
discover and call it, and the client is a plain `google.golang.org/grpc` client
with no go-micro SDK.
This is the setup behind [micro/go-micro#4880](https://github.com/micro/go-micro/issues/4880).
## How it works
go-micro's gRPC server routes every call by parsing the standard gRPC method path
(`/helloworld.Say/Hello`) and dispatches it to the matching go-micro handler. The
`grpcserver.Reflection()` option additionally registers each handler with gRPC's
reflection service, so tools can `list` and `describe` the service without
injecting a raw `grpc.Server`.
## Running
Start the server:
```bash
cd examples/grpc
go run .
```
In another terminal, call it with the standard gRPC client:
```bash
cd examples/grpc
go run ./client --name Alice
# Response: Hello Alice
```
Or with grpcurl:
```bash
grpcurl -plaintext localhost:8080 list
# helloworld.Say
grpcurl -plaintext -d '{"name":"World"}' localhost:8080 helloworld.Say.Hello
# { "message": "Hello World" }
```
## Service name
The registry name (`helloworld`) lives on the gRPC server via
`server.Name("helloworld")`. Pass it there rather than only to
`micro.NewService("helloworld", ...)``micro.NewService` prepends its `Name`
option, which gets discarded when the default server is swapped out.
## Regenerating the proto
```bash
protoc -I proto \
--go_out=proto --go_opt=paths=source_relative \
--micro_out=proto --micro_opt=paths=source_relative \
--go-grpc_out=proto --go-grpc_opt=paths=source_relative \
proto/helloworld.proto
```
`protoc-gen-micro` must be v6: `go install go-micro.dev/v6/cmd/protoc-gen-micro@latest`.
+38
View File
@@ -0,0 +1,38 @@
// client calls the go-micro helloworld service using a standard gRPC client
// — no go-micro SDK. This proves any gRPC client (grpcurl, Python, Java, ...)
// can call a go-micro service.
package main
import (
"context"
"flag"
"fmt"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "example/proto"
)
func main() {
addr := flag.String("addr", "localhost:8080", "server address")
name := flag.String("name", "World", "name to greet")
flag.Parse()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conn, err := grpc.NewClient(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("connect: %v", err)
}
defer conn.Close()
resp, err := pb.NewSayClient(conn).Hello(ctx, &pb.Request{Name: *name})
if err != nil {
log.Fatalf("Say.Hello: %v", err)
}
fmt.Printf("Response: %s\n", resp.Message)
}
+74
View File
@@ -0,0 +1,74 @@
module example
go 1.25.0
require (
go-micro.dev/v6 v6.9.0
google.golang.org/grpc v1.82.1
google.golang.org/protobuf v1.36.11
)
require (
dario.cat/mergo v1.0.2 // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/bitly/go-simplejson v0.5.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coreos/go-semver v0.3.0 // indirect
github.com/coreos/go-systemd/v22 v22.3.2 // indirect
github.com/cornelk/hashmap v1.0.8 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/fatih/color v1.16.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-redis/redis/v8 v8.11.5 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/consul/api v1.32.1 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-hclog v1.5.0 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/serf v0.10.1 // indirect
github.com/klauspost/compress v1.18.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/miekg/dns v1.1.50 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/hashstructure v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/nats-io/nats.go v1.42.0 // indirect
github.com/nats-io/nkeys v0.4.11 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rabbitmq/amqp091-go v1.10.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/urfave/cli/v2 v2.27.6 // indirect
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
go.etcd.io/bbolt v1.4.0 // indirect
go.etcd.io/etcd/api/v3 v3.5.21 // indirect
go.etcd.io/etcd/client/pkg/v3 v3.5.21 // indirect
go.etcd.io/etcd/client/v3 v3.5.21 // indirect
go.opentelemetry.io/otel v1.43.0 // indirect
go.opentelemetry.io/otel/trace v1.43.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.53.0 // indirect
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect
golang.org/x/mod v0.37.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.39.0 // indirect
golang.org/x/tools v0.47.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
)
replace go-micro.dev/v6 => ../..
+387
View File
@@ -0,0 +1,387 @@
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-metrics v0.4.1 h1:hR91U9KYmb6bLBYLQjyM+3j+rcd/UhE+G78SFnF8gJA=
github.com/armon/go-metrics v0.4.1/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+3JqfkOG4=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bitly/go-simplejson v0.5.0 h1:6IH+V8/tVMab511d5bn4M7EwGXZf9Hj6i2xSwkNEM+Y=
github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag=
github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I=
github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd/v22 v22.3.2 h1:D9/bQk5vlXQFZ6Kwuu6zaiXJ9oTPe68++AzAJc1DzSI=
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cornelk/hashmap v1.0.8 h1:nv0AWgw02n+iDcawr5It4CjQIAcdMMKRrs10HOJYlrc=
github.com/cornelk/hashmap v1.0.8/go.mod h1:RfZb7JO3RviW/rT6emczVuC/oxpdz4UsSB2LJSclR1k=
github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc=
github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.1 h1:gK4Kx5IaGY9CD5sPJ36FHiBJ6ZXl0kilRiiCj+jdYp4=
github.com/google/btree v1.0.1/go.mod h1:xXMiIv4Fb/0kKde4SpL7qlzvu5cMJDRkFDxJfI9uaxA=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/go-tpm v0.9.3 h1:+yx0/anQuGzi+ssRqeD6WpXjW2L/V0dItUayO0i9sRc=
github.com/google/go-tpm v0.9.3/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/consul/api v1.32.1 h1:0+osr/3t/aZNAdJX558crU3PEjVrG4x6715aZHRgceE=
github.com/hashicorp/consul/api v1.32.1/go.mod h1:mXUWLnxftwTmDv4W3lzxYCPD199iNLLUyLfLGFJbtl4=
github.com/hashicorp/consul/sdk v0.16.1 h1:V8TxTnImoPD5cj0U9Spl0TUxcytjcbbJeADFF07KdHg=
github.com/hashicorp/consul/sdk v0.16.1/go.mod h1:fSXvwxB2hmh1FMZCNl6PwX0Q/1wdWtHJcZ7Ea5tns0s=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c=
github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc=
github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-msgpack v0.5.5 h1:i9R9JSrqIz0QVLz3sz+i3YJdT7TTSLcfLLzJi9aZTuI=
github.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs=
github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc=
github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-sockaddr v1.0.2 h1:ztczhD1jLxIRjVejw8gFomI1BQZOe2WoVOu0SyteCQc=
github.com/hashicorp/go-sockaddr v1.0.2/go.mod h1:rB4wwRAUzs07qva3c5SdrY/NEtAUjGlgmH/UkBUC97A=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-version v1.2.1 h1:zEfKbn2+PDgroKdiOzqiE8rsmLqU2uwi5PB5pBJ3TkI=
github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c=
github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.4/go.mod h1:mtBihi+LeNXGtG8L9dX59gAEa12BDtBQSp4v/YAJqrc=
github.com/hashicorp/memberlist v0.5.0 h1:EtYPN8DpAURiapus508I4n9CzHs2W+8NZGbmmR/prTM=
github.com/hashicorp/memberlist v0.5.0/go.mod h1:yvyXLpo0QaGE59Y7hDTsTzDD25JYBZ4mHgHUZ8lrOI0=
github.com/hashicorp/serf v0.10.1 h1:Z1H2J60yRKvfDYAOZLd2MU0ND4AH/WDz7xYHDWQsIPY=
github.com/hashicorp/serf v0.10.1/go.mod h1:yL2t6BqATOLGc5HF7qbFkTfXoPIY0WZdWHfEvMqbG+4=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI=
github.com/miekg/dns v1.1.50 h1:DQUfb9uc6smULcREF09Uc+/Gd46YWqJd5DbpPE9xkcA=
github.com/miekg/dns v1.1.50/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME=
github.com/minio/highwayhash v1.0.3 h1:kbnuUMoHYyVl7szWjSxJnxw11k2U709jqFPPmIUyD6Q=
github.com/minio/highwayhash v1.0.3/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/hashstructure v1.1.0 h1:P6P1hdjqAAknpY/M1CGipelZgp+4y9ja9kmUZPXP+H0=
github.com/mitchellh/hashstructure v1.1.0/go.mod h1:xUDAozZz0Wmdiufv0uyhnHkUTN6/6d8ulp4AwfLKrmA=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nats-io/jwt/v2 v2.7.4 h1:jXFuDDxs/GQjGDZGhNgH4tXzSUK6WQi2rsj4xmsNOtI=
github.com/nats-io/jwt/v2 v2.7.4/go.mod h1:me11pOkwObtcBNR8AiMrUbtVOUGkqYjMQZ6jnSdVUIA=
github.com/nats-io/nats-server/v2 v2.11.3 h1:AbGtXxuwjo0gBroLGGr/dE0vf24kTKdRnBq/3z/Fdoc=
github.com/nats-io/nats-server/v2 v2.11.3/go.mod h1:6Z6Fd+JgckqzKig7DYwhgrE7bJ6fypPHnGPND+DqgMY=
github.com/nats-io/nats.go v1.42.0 h1:ynIMupIOvf/ZWH/b2qda6WGKGNSjwOUutTpWRvAmhaM=
github.com/nats-io/nats.go v1.42.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g=
github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0=
github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/test-go/testify v1.1.4 h1:Tf9lntrKUMHiXQ07qBScBTSA0dhYQlu83hswqelv1iE=
github.com/test-go/testify v1.1.4/go.mod h1:rH7cfJo/47vWGdi4GPj16x3/t1xGOj2YxzmNQzk2ghU=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
github.com/urfave/cli/v2 v2.27.6 h1:VdRdS98FNhKZ8/Az8B7MTyGQmpIr36O1EHybx/LaZ4g=
github.com/urfave/cli/v2 v2.27.6/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5hrMvTQ=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.etcd.io/bbolt v1.4.0 h1:TU77id3TnN/zKr7CO/uk+fBCwF2jGcMuw2B/FMAzYIk=
go.etcd.io/bbolt v1.4.0/go.mod h1:AsD+OCi/qPN1giOX1aiLAha3o1U8rAz65bvN4j0sRuk=
go.etcd.io/etcd/api/v3 v3.5.21 h1:A6O2/JDb3tvHhiIz3xf9nJ7REHvtEFJJ3veW3FbCnS8=
go.etcd.io/etcd/api/v3 v3.5.21/go.mod h1:c3aH5wcvXv/9dqIw2Y810LDXJfhSYdHQ0vxmP3CCHVY=
go.etcd.io/etcd/client/pkg/v3 v3.5.21 h1:lPBu71Y7osQmzlflM9OfeIV2JlmpBjqBNlLtcoBqUTc=
go.etcd.io/etcd/client/pkg/v3 v3.5.21/go.mod h1:BgqT/IXPjK9NkeSDjbzwsHySX3yIle2+ndz28nVsjUs=
go.etcd.io/etcd/client/v3 v3.5.21 h1:T6b1Ow6fNjOLOtM0xSoKNQt1ASPCLWrF9XMHcH9pEyY=
go.etcd.io/etcd/client/v3 v3.5.21/go.mod h1:mFYy67IOqmbRf/kRUvsHixzo3iG+1OF2W2+jVIQRAnU=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210303074136-134d130e1a04/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0=
golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec=
google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+50
View File
@@ -0,0 +1,50 @@
// server starts a go-micro gRPC service and enables the reflection API, so
// any standard gRPC client (grpcurl, grpc_cli, Postman, Go, Python, Java,
// ...) can discover and call it — no go-micro SDK required on the client.
package main
import (
"context"
"fmt"
"log"
micro "go-micro.dev/v6"
"go-micro.dev/v6/server"
grpcserver "go-micro.dev/v6/server/grpc"
pb "example/proto"
)
type Say struct{}
func (s *Say) Hello(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
rsp.Message = "Hello " + req.Name
return nil
}
func main() {
service := micro.NewService("helloworld",
micro.Server(grpcserver.NewServer(
// The registry name lives on the gRPC server, not on
// micro.NewService, otherwise it is lost when the default
// server is swapped out.
server.Name("helloworld"),
server.Address(":8080"),
// Expose the reflection API so grpcurl and friends can
// list and describe the service.
grpcserver.Reflection(),
)),
)
service.Init()
if err := pb.RegisterSayHandler(service.Server(), &Say{}); err != nil {
log.Fatal(err)
}
fmt.Println("go-micro gRPC server listening on :8080 (service: helloworld)")
fmt.Println("List services: grpcurl -plaintext localhost:8080 list")
if err := service.Run(); err != nil {
log.Fatal(err)
}
}
+174
View File
@@ -0,0 +1,174 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.10
// protoc v5.26.1
// source: proto/helloworld.proto
package helloworld
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 Request struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Request) Reset() {
*x = Request{}
mi := &file_proto_helloworld_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Request) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Request) ProtoMessage() {}
func (x *Request) ProtoReflect() protoreflect.Message {
mi := &file_proto_helloworld_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 Request.ProtoReflect.Descriptor instead.
func (*Request) Descriptor() ([]byte, []int) {
return file_proto_helloworld_proto_rawDescGZIP(), []int{0}
}
func (x *Request) GetName() string {
if x != nil {
return x.Name
}
return ""
}
type Response 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 *Response) Reset() {
*x = Response{}
mi := &file_proto_helloworld_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Response) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Response) ProtoMessage() {}
func (x *Response) ProtoReflect() protoreflect.Message {
mi := &file_proto_helloworld_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 Response.ProtoReflect.Descriptor instead.
func (*Response) Descriptor() ([]byte, []int) {
return file_proto_helloworld_proto_rawDescGZIP(), []int{1}
}
func (x *Response) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
var File_proto_helloworld_proto protoreflect.FileDescriptor
const file_proto_helloworld_proto_rawDesc = "" +
"\n" +
"\x16proto/helloworld.proto\x12\n" +
"helloworld\"\x1d\n" +
"\aRequest\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"$\n" +
"\bResponse\x12\x18\n" +
"\amessage\x18\x01 \x01(\tR\amessage2;\n" +
"\x03Say\x124\n" +
"\x05Hello\x12\x13.helloworld.Request\x1a\x14.helloworld.Response\"\x00B\x14Z\x12./proto;helloworldb\x06proto3"
var (
file_proto_helloworld_proto_rawDescOnce sync.Once
file_proto_helloworld_proto_rawDescData []byte
)
func file_proto_helloworld_proto_rawDescGZIP() []byte {
file_proto_helloworld_proto_rawDescOnce.Do(func() {
file_proto_helloworld_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_helloworld_proto_rawDesc), len(file_proto_helloworld_proto_rawDesc)))
})
return file_proto_helloworld_proto_rawDescData
}
var file_proto_helloworld_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_proto_helloworld_proto_goTypes = []any{
(*Request)(nil), // 0: helloworld.Request
(*Response)(nil), // 1: helloworld.Response
}
var file_proto_helloworld_proto_depIdxs = []int32{
0, // 0: helloworld.Say.Hello:input_type -> helloworld.Request
1, // 1: helloworld.Say.Hello:output_type -> helloworld.Response
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proto_helloworld_proto_init() }
func file_proto_helloworld_proto_init() {
if File_proto_helloworld_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_helloworld_proto_rawDesc), len(file_proto_helloworld_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_proto_helloworld_proto_goTypes,
DependencyIndexes: file_proto_helloworld_proto_depIdxs,
MessageInfos: file_proto_helloworld_proto_msgTypes,
}.Build()
File_proto_helloworld_proto = out.File
file_proto_helloworld_proto_goTypes = nil
file_proto_helloworld_proto_depIdxs = nil
}
@@ -0,0 +1,79 @@
// Code generated by protoc-gen-micro. DO NOT EDIT.
// source: proto/helloworld.proto
package helloworld
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 Say service
type SayService interface {
Hello(ctx context.Context, in *Request, opts ...client.CallOption) (*Response, error)
}
type sayService struct {
c client.Client
name string
}
func NewSayService(name string, c client.Client) SayService {
return &sayService{
c: c,
name: name,
}
}
func (c *sayService) Hello(ctx context.Context, in *Request, opts ...client.CallOption) (*Response, error) {
req := c.c.NewRequest(c.name, "Say.Hello", in)
out := new(Response)
err := c.c.Call(ctx, req, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Say service
type SayHandler interface {
Hello(context.Context, *Request, *Response) error
}
func RegisterSayHandler(s server.Server, hdlr SayHandler, opts ...server.HandlerOption) error {
type say interface {
Hello(ctx context.Context, in *Request, out *Response) error
}
type Say struct {
say
}
h := &sayHandler{hdlr}
return s.Handle(s.NewHandler(&Say{h}, opts...))
}
type sayHandler struct {
SayHandler
}
func (h *sayHandler) Hello(ctx context.Context, in *Request, out *Response) error {
return h.SayHandler.Hello(ctx, in, out)
}
+16
View File
@@ -0,0 +1,16 @@
syntax = "proto3";
package helloworld;
option go_package = "./proto;helloworld";
service Say {
rpc Hello(Request) returns (Response) {}
}
message Request {
string name = 1;
}
message Response {
string message = 1;
}
+121
View File
@@ -0,0 +1,121 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v5.26.1
// source: helloworld.proto
package helloworld
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Say_Hello_FullMethodName = "/helloworld.Say/Hello"
)
// SayClient is the client API for Say service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type SayClient interface {
Hello(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
}
type sayClient struct {
cc grpc.ClientConnInterface
}
func NewSayClient(cc grpc.ClientConnInterface) SayClient {
return &sayClient{cc}
}
func (c *sayClient) Hello(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(Response)
err := c.cc.Invoke(ctx, Say_Hello_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// SayServer is the server API for Say service.
// All implementations must embed UnimplementedSayServer
// for forward compatibility.
type SayServer interface {
Hello(context.Context, *Request) (*Response, error)
mustEmbedUnimplementedSayServer()
}
// UnimplementedSayServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedSayServer struct{}
func (UnimplementedSayServer) Hello(context.Context, *Request) (*Response, error) {
return nil, status.Errorf(codes.Unimplemented, "method Hello not implemented")
}
func (UnimplementedSayServer) mustEmbedUnimplementedSayServer() {}
func (UnimplementedSayServer) testEmbeddedByValue() {}
// UnsafeSayServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to SayServer will
// result in compilation errors.
type UnsafeSayServer interface {
mustEmbedUnimplementedSayServer()
}
func RegisterSayServer(s grpc.ServiceRegistrar, srv SayServer) {
// If the following call pancis, it indicates UnimplementedSayServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Say_ServiceDesc, srv)
}
func _Say_Hello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Request)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SayServer).Hello(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Say_Hello_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SayServer).Hello(ctx, req.(*Request))
}
return interceptor(ctx, in, info, handler)
}
// Say_ServiceDesc is the grpc.ServiceDesc for Say service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Say_ServiceDesc = grpc.ServiceDesc{
ServiceName: "helloworld.Say",
HandlerType: (*SayServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Hello",
Handler: _Say_Hello_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "helloworld.proto",
}
+4 -1
View File
@@ -92,7 +92,10 @@ func (f *Flow) runStepSpan(ctx context.Context, step Step, in State) (State, int
span.SetAttributes(attribute.String(AttrFlowVerificationStatus, "failed"))
}
}
if err != nil {
if a, ok := isAwaitInput(err); ok {
// A suspend is normal control flow, not a step error.
span.SetStatus(codes.Ok, "waiting: "+a.Key)
} else if err != nil {
span.RecordError(err)
span.SetAttributes(attribute.String(AttrFlowErrorKind, string(ai.ClassifyError(err))))
span.SetStatus(codes.Error, err.Error())
+136 -2
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"text/template"
@@ -110,7 +111,8 @@ type Run struct {
Flow string `json:"flow"`
State State `json:"state"`
Steps []StepRecord `json:"steps"`
Status string `json:"status"` // running | done | failed
Status string `json:"status"` // running | waiting | done | failed
Await *AwaitState `json:"await,omitempty"`
Started time.Time `json:"started"`
Updated time.Time `json:"updated"`
}
@@ -336,6 +338,54 @@ func LLM(prompt string) StepFunc {
}
}
// AwaitInput is the control signal a step returns (via Await) to suspend a run
// pending external input. runFrom recognizes it, checkpoints the run as
// "waiting", and returns cleanly — a suspend is not a failure. ResumeWith
// injects the input and continues.
type AwaitInput struct {
Key string // labels what is awaited (e.g. "approval")
Prompt string // human-facing description of the input needed
}
func (e *AwaitInput) Error() string {
if e.Prompt != "" {
return fmt.Sprintf("flow: awaiting input %q: %s", e.Key, e.Prompt)
}
return fmt.Sprintf("flow: awaiting input %q", e.Key)
}
// AwaitState records, on a suspended run, what it is waiting for.
type AwaitState struct {
Step string `json:"step"`
Key string `json:"key"`
Prompt string `json:"prompt,omitempty"`
}
func isAwaitInput(err error) (*AwaitInput, bool) {
var a *AwaitInput
if errors.As(err, &a) {
return a, true
}
return nil, false
}
// Await is a StepFunc that suspends the run pending external input. The run is
// checkpointed with status "waiting" and returned cleanly; a later call to
// Flow.ResumeWith(ctx, runID, input) completes this step with the injected
// input and continues to the next step. key labels what is awaited (surfaced on
// the run and via Flow.Waiting); prompt describes the input needed.
func Await(key, prompt string) StepFunc {
return func(_ context.Context, in State) (State, error) {
return in, &AwaitInput{Key: key, Prompt: prompt}
}
}
// AwaitStep is a convenience for a named await step:
// Step{Name: name, Run: Await(key, prompt)}.
func AwaitStep(name, key, prompt string) Step {
return Step{Name: name, Run: Await(key, prompt)}
}
// startRun begins a fresh run of the flow's steps with the given input.
func (f *Flow) startRun(ctx context.Context, data string) (Run, error) {
if err := validateSteps(f.opts.Steps); err != nil {
@@ -421,13 +471,79 @@ func (f *Flow) Pending(ctx context.Context) ([]Run, error) {
}
var out []Run
for _, r := range all {
if r.Flow == f.name && r.Status != "done" {
// Waiting runs need injected input (ResumeWith), not a restart, so a
// recovery loop (ResumePending) should not pick them up.
if r.Flow == f.name && r.Status != "done" && r.Status != "waiting" {
out = append(out, r)
}
}
return out, nil
}
// Waiting returns this flow's runs suspended awaiting external input, each with
// its Await metadata, so a caller can prompt for and inject the needed input
// with ResumeWith.
func (f *Flow) Waiting(ctx context.Context) ([]Run, error) {
if f.checkpoint == nil {
return nil, nil
}
all, err := f.checkpoint.List(ctx)
if err != nil {
return nil, err
}
var out []Run
for _, r := range all {
if r.Flow == f.name && r.Status == "waiting" {
out = append(out, r)
}
}
return out, nil
}
// ResumeWith completes a suspended (waiting) run: it injects input for the
// awaited step — the input becomes that step's output state — and continues
// from the next step. It errors if the run is not waiting for input.
func (f *Flow) ResumeWith(ctx context.Context, runID, input string) error {
ctx, cancel := f.withTimeout(ctx)
defer cancel()
if err := validateSteps(f.opts.Steps); err != nil {
return err
}
if f.checkpoint == nil {
return fmt.Errorf("flow %s has no checkpoint configured", f.name)
}
run, ok, err := f.checkpoint.Load(ctx, runID)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("run %s not found", runID)
}
if run.Status != "waiting" {
return fmt.Errorf("run %s is not waiting for input (status %q)", runID, run.Status)
}
steps := f.opts.Steps
i := stepIndex(steps, run.State.Stage)
if i < 0 {
return fmt.Errorf("run %s is waiting at unknown step %q", runID, run.State.Stage)
}
// The awaited step is satisfied by the injected input; record it done and
// advance so runFrom re-enters at the next step.
run.Steps[i].Status = "done"
run.Steps[i].Result = truncate(input, 200)
run.State.Data = []byte(input)
if i+1 < len(steps) {
run.State.Stage = steps[i+1].Name
} else {
run.State.Stage = ""
}
run.Await = nil
run.Status = "running"
_, err = f.runFrom(ctx, run)
return err
}
// runFrom executes steps from the run's current Stage to the end,
// checkpointing before and after each step.
func (f *Flow) runFrom(ctx context.Context, run Run) (Run, error) {
@@ -464,6 +580,19 @@ func (f *Flow) runFrom(ctx context.Context, run Run) (Run, error) {
out, attempts, verification, err := f.runStepSpan(ctx, step, run.State)
run.Steps[i].Attempts = attempts
applyVerificationRecord(&run.Steps[i], verification)
if await, ok := isAwaitInput(err); ok {
// Suspend the run pending external input — checkpoint and return
// cleanly (not a failure). ResumeWith injects the input later.
run.Steps[i].Status = "waiting"
run.Status = "waiting"
run.Await = &AwaitState{Step: step.Name, Key: await.Key, Prompt: await.Prompt}
if saveErr := f.save(ctx, run); saveErr != nil {
spanErr = saveErr
return run, saveErr
}
f.log.Logf(logger.InfoLevel, "Flow %s run %s waiting for input %q at step %q", f.name, run.ID, await.Key, step.Name)
return run, nil
}
if err != nil {
spanErr = err
run.Steps[i].Status = "failed"
@@ -537,6 +666,11 @@ func (f *Flow) runStep(ctx context.Context, step Step, in State) (State, int, Ve
attemptCtx = ai.WithRunInfo(ctx, info)
}
out, err := step.Run(attemptCtx, in)
// An await signal is control flow, not a failure: suspend immediately
// without retrying or grading.
if _, ok := isAwaitInput(err); ok {
return in, attempt, lastVerification, err
}
if err == nil && step.Verify != nil {
lastVerification, err = step.Verify(attemptCtx, out)
if err == nil && !lastVerification.Passed {
+87
View File
@@ -87,6 +87,93 @@ func TestFlowCheckpointResume(t *testing.T) {
}
}
func TestFlowAwaitAndResumeWith(t *testing.T) {
mem := store.NewMemoryStore()
var firstCalls int
var secondInput string
steps := []Step{
{Name: "first", Run: func(_ context.Context, in State) (State, error) {
firstCalls++
in.Data = []byte("first-done")
return in, nil
}},
AwaitStep("approval", "approve", "Approve to continue?"),
{Name: "second", Run: func(_ context.Context, in State) (State, error) {
secondInput = in.String()
in.Data = []byte("second-done")
return in, nil
}},
}
f := New("hitl", WithCheckpoint(StoreCheckpoint(mem, "hitl")), Steps(steps...))
// Execute suspends at the await step — a clean return, not an error.
if err := f.Execute(context.Background(), "start"); err != nil {
t.Fatalf("Execute should suspend cleanly, got %v", err)
}
if firstCalls != 1 {
t.Fatalf("first step calls = %d, want 1", firstCalls)
}
// A waiting run is not pending (restart), it needs input.
if pend, _ := f.Pending(context.Background()); len(pend) != 0 {
t.Errorf("a waiting run must not be pending, got %d", len(pend))
}
waiting, err := f.Waiting(context.Background())
if err != nil {
t.Fatal(err)
}
if len(waiting) != 1 {
t.Fatalf("waiting runs = %d, want 1", len(waiting))
}
w := waiting[0]
if w.Status != "waiting" || w.Await == nil || w.Await.Key != "approve" ||
w.Await.Prompt != "Approve to continue?" || w.Await.Step != "approval" {
t.Fatalf("await metadata = %+v (status %q)", w.Await, w.Status)
}
if w.State.Stage != "approval" {
t.Fatalf("waiting stage = %q, want approval", w.State.Stage)
}
// Injecting input completes the awaited step and runs the rest.
if err := f.ResumeWith(context.Background(), w.ID, "approved"); err != nil {
t.Fatalf("ResumeWith: %v", err)
}
if firstCalls != 1 {
t.Errorf("completed step re-ran on resume; first calls = %d", firstCalls)
}
if secondInput != "approved" {
t.Errorf("second step input = %q, want the injected 'approved'", secondInput)
}
if wr, _ := f.Waiting(context.Background()); len(wr) != 0 {
t.Errorf("no waiting runs after resume, got %d", len(wr))
}
runs, _ := StoreCheckpoint(mem, "hitl").List(context.Background())
if len(runs) != 1 || runs[0].Status != "done" {
t.Fatalf("run should be done after resume, got %+v", runs)
}
if runs[0].Await != nil {
t.Errorf("await metadata should be cleared after resume, got %+v", runs[0].Await)
}
}
func TestFlowResumeWithRejectsNonWaiting(t *testing.T) {
mem := store.NewMemoryStore()
f := New("hitl2", WithCheckpoint(StoreCheckpoint(mem, "hitl2")),
Steps(Step{Name: "only", Run: func(_ context.Context, in State) (State, error) { return in, nil }}))
if err := f.Execute(context.Background(), "x"); err != nil {
t.Fatalf("Execute: %v", err)
}
runs, _ := StoreCheckpoint(mem, "hitl2").List(context.Background())
if len(runs) != 1 {
t.Fatalf("runs = %d", len(runs))
}
if err := f.ResumeWith(context.Background(), runs[0].ID, "input"); err == nil {
t.Error("ResumeWith on a completed (non-waiting) run should error")
}
}
func TestFlowStepContextIncludesRunInfo(t *testing.T) {
var got ai.RunInfo
step := Step{Name: "inspect", Run: func(ctx context.Context, in State) (State, error) {
+209 -44
View File
@@ -27,12 +27,14 @@ package a2a
import (
"context"
"crypto/ed25519"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
@@ -64,6 +66,20 @@ type Options struct {
Client client.Client
// Logger for startup/debug output (defaults to log.Default()).
Logger *log.Logger
// AllowPushURL authorizes an outbound push-notification callback URL
// (tasks/pushNotificationConfig/set). Return a non-nil error to reject it.
// When nil, a default SSRF-safe policy applies: only http/https URLs whose
// host does not resolve to a loopback, private, link-local, or unspecified
// address are allowed, and the connection is pinned to that check at dial
// time (DNS-rebinding safe). Set this to permit a trusted in-cluster
// receiver, or to narrow delivery to an allowlist.
AllowPushURL func(*url.URL) error
// AP2PublicKey, when set, verifies AP2 payment/checkout mandates carried on
// incoming A2A messages against this Ed25519 key and records the outcome in
// each task's ap2Verifications (signature + task/context binding). When
// unset, mandates are carried through unverified. This is opt-in so the
// default flow stays free of a payment trust decision.
AP2PublicKey ed25519.PublicKey
}
// Gateway serves the A2A protocol over HTTP for the registry's agents.
@@ -87,7 +103,20 @@ func New(opts Options) *Gateway {
opts.BaseURL = "http://localhost" + opts.Address
}
opts.BaseURL = strings.TrimRight(opts.BaseURL, "/")
return &Gateway{opts: opts, disp: newDispatcher()}
g := &Gateway{opts: opts, disp: newDispatcher()}
if opts.AllowPushURL != nil {
// Operator owns the trust decision: use their policy and skip the
// built-in private-IP dial guard so trusted in-cluster hosts resolve.
g.disp.allowPushURL = opts.AllowPushURL
g.disp.guardPushDial = false
}
if len(opts.AP2PublicKey) > 0 {
pub := opts.AP2PublicKey
g.disp.ap2Verify = func(s AP2SignedMandate, task Task) AP2Verification {
return VerifyAP2ForTask(s, pub, task, nil)
}
}
return g
}
// Invoke runs an agent for one message and returns its reply. It is the
@@ -98,16 +127,55 @@ type Invoke func(ctx context.Context, text string) (string, error)
// StreamInvoke runs an agent for one message and returns streaming output chunks.
type StreamInvoke func(ctx context.Context, text string) (ai.Stream, error)
// AgentHandlerOption configures an embedded A2A agent handler.
type AgentHandlerOption func(*dispatcher)
// WithPushURLPolicy sets the push-notification callback URL policy for an
// embedded agent handler (the analog of Options.AllowPushURL on the gateway).
// Return a non-nil error to reject a URL. Without it, the default SSRF-safe
// policy applies. Supplying a policy also disables the built-in private-IP dial
// guard, so a trusted in-cluster receiver resolves.
func WithPushURLPolicy(allow func(*url.URL) error) AgentHandlerOption {
return func(d *dispatcher) {
if allow == nil {
return
}
d.allowPushURL = allow
d.guardPushDial = false
}
}
// WithAP2PublicKey verifies AP2 mandates carried on incoming messages against
// pub (the embedded-handler analog of Options.AP2PublicKey), recording the
// outcome in each task's ap2Verifications. Without it, mandates are carried
// unverified.
func WithAP2PublicKey(pub ed25519.PublicKey) AgentHandlerOption {
return func(d *dispatcher) {
if len(pub) == 0 {
return
}
d.ap2Verify = func(s AP2SignedMandate, task Task) AP2Verification {
return VerifyAP2ForTask(s, pub, task, nil)
}
}
}
// NewAgentHandler returns an http.Handler that serves the A2A protocol
// for a single agent: its Agent Card at / and /.well-known/agent.json,
// and the JSON-RPC endpoint at /. invoke runs the agent. This is what an
// agent embeds to speak A2A directly, without a separate gateway.
func NewAgentHandler(card AgentCard, invoke Invoke) http.Handler {
func NewAgentHandler(card AgentCard, invoke Invoke, opts ...AgentHandlerOption) http.Handler {
d := newDispatcher()
for _, o := range opts {
o(d)
}
mux := http.NewServeMux()
card.URL = strings.TrimRight(card.URL, "/")
serveCard := func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, card) }
mux.HandleFunc("GET /{$}", serveCard)
// A2A 0.3.0 discovery is /.well-known/agent-card.json; agent.json is the
// pre-0.3 alias, kept so existing clients don't break.
mux.HandleFunc("GET /.well-known/agent-card.json", serveCard)
mux.HandleFunc("GET /.well-known/agent.json", serveCard)
mux.HandleFunc("POST /{$}", func(w http.ResponseWriter, r *http.Request) { d.serve(w, r, invoke) })
return mux
@@ -115,12 +183,16 @@ func NewAgentHandler(card AgentCard, invoke Invoke) http.Handler {
// NewAgentStreamHandler is like NewAgentHandler, but serves A2A message/stream
// by forwarding model chunks as server-sent task updates when stream is non-nil.
func NewAgentStreamHandler(card AgentCard, invoke Invoke, stream StreamInvoke) http.Handler {
func NewAgentStreamHandler(card AgentCard, invoke Invoke, stream StreamInvoke, opts ...AgentHandlerOption) http.Handler {
d := newDispatcher()
for _, o := range opts {
o(d)
}
mux := http.NewServeMux()
card.URL = strings.TrimRight(card.URL, "/")
serveCard := func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, card) }
mux.HandleFunc("GET /{$}", serveCard)
mux.HandleFunc("GET /.well-known/agent-card.json", serveCard)
mux.HandleFunc("GET /.well-known/agent.json", serveCard)
mux.HandleFunc("POST /{$}", func(w http.ResponseWriter, r *http.Request) { d.serveWithStream(w, r, invoke, stream) })
return mux
@@ -139,15 +211,19 @@ func (g *Gateway) Handler() http.Handler {
// Discovery: a directory of all agent cards.
mux.HandleFunc("GET /agents", g.handleList)
// Per-agent card (served at the agent's url and at its well-known path).
// A2A 0.3.0 uses agent-card.json; agent.json is the pre-0.3 alias.
mux.HandleFunc("GET /agents/{name}", g.handleCard)
mux.HandleFunc("GET /agents/{name}/.well-known/agent-card.json", g.handleCard)
mux.HandleFunc("GET /agents/{name}/.well-known/agent.json", g.handleCard)
mux.HandleFunc("GET /agents/{name}/skills/{skill}", g.handleSkillCard)
mux.HandleFunc("GET /agents/{name}/skills/{skill}/.well-known/agent-card.json", g.handleSkillCard)
mux.HandleFunc("GET /agents/{name}/skills/{skill}/.well-known/agent.json", g.handleSkillCard)
// Per-agent JSON-RPC endpoint.
mux.HandleFunc("POST /agents/{name}", g.handleRPC)
mux.HandleFunc("POST /agents/{name}/skills/{skill}", g.handleSkillRPC)
// Top-level well-known: serve the single agent's card if there's
// exactly one, otherwise point to the directory.
mux.HandleFunc("GET /.well-known/agent-card.json", g.handleWellKnown)
mux.HandleFunc("GET /.well-known/agent.json", g.handleWellKnown)
return mux
}
@@ -222,6 +298,39 @@ type Artifact struct {
Parts []Part `json:"parts"`
}
// TaskStatusUpdateEvent is an A2A streaming event reporting a change in a
// task's status. External SSE clients parse stream events by `kind` and stop
// on the event whose `final` is true — a full Task snapshot (which older
// versions emitted) carries neither, so strict clients never terminate.
type TaskStatusUpdateEvent struct {
TaskID string `json:"taskId"`
ContextID string `json:"contextId"`
Kind string `json:"kind"` // "status-update"
Status TaskStatus `json:"status"`
Final bool `json:"final"`
}
// TaskArtifactUpdateEvent is an A2A streaming event carrying an artifact (or,
// with Append, one incremental chunk of one).
type TaskArtifactUpdateEvent struct {
TaskID string `json:"taskId"`
ContextID string `json:"contextId"`
Kind string `json:"kind"` // "artifact-update"
Artifact Artifact `json:"artifact"`
Append bool `json:"append,omitempty"`
LastChunk bool `json:"lastChunk,omitempty"`
}
func statusUpdateEvent(t *Task, final bool) TaskStatusUpdateEvent {
return TaskStatusUpdateEvent{
TaskID: t.ID,
ContextID: t.ContextID,
Kind: "status-update",
Status: t.Status,
Final: final,
}
}
// Task is the unit of work returned by message/send and tasks/get.
type Task struct {
ID string `json:"id"`
@@ -469,10 +578,26 @@ type dispatcher struct {
pushConfigs map[string]PushNotificationConfig
watchers map[string]map[chan *Task]struct{}
order []string // task ids in insertion order, for bounded eviction
// allowPushURL authorizes an outbound push-notification callback URL; nil
// means the default SSRF-safe policy. guardPushDial applies the private-IP
// dial guard (on unless an operator supplied a custom policy).
allowPushURL func(*url.URL) error
guardPushDial bool
// ap2Verify, when non-nil, verifies each AP2 mandate carried on a task and
// records the result in the task's AP2Verifications. Nil = carry unverified.
ap2Verify func(AP2SignedMandate, Task) AP2Verification
}
func newDispatcher() *dispatcher {
return &dispatcher{tasks: map[string]*Task{}, pushConfigs: map[string]PushNotificationConfig{}, watchers: map[string]map[chan *Task]struct{}{}}
return &dispatcher{
tasks: map[string]*Task{},
pushConfigs: map[string]PushNotificationConfig{},
watchers: map[string]map[chan *Task]struct{}{},
allowPushURL: defaultPushURLPolicy,
guardPushDial: true,
}
}
func (d *dispatcher) serve(w http.ResponseWriter, r *http.Request, invoke Invoke) {
@@ -534,14 +659,11 @@ func (d *dispatcher) stream(ctx context.Context, w http.ResponseWriter, req rpcR
writeRPC(w, req.ID, nil, e)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(sseWriter{w: w}).Encode(rpcResponse{JSONRPC: "2.0", ID: req.ID, Result: task})
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
enc, flush := sseResponse(w)
// The Task snapshot first (carries ids and the final artifact), then a
// terminal status-update so external SSE clients see `final:true` and stop.
writeSSE(enc, flush, req.ID, task)
writeSSE(enc, flush, req.ID, statusUpdateEvent(task, true))
}
func (d *dispatcher) streamChunks(ctx context.Context, w http.ResponseWriter, req rpcRequest, invoke StreamInvoke, fallback Invoke) {
@@ -565,46 +687,53 @@ func (d *dispatcher) streamChunks(ctx context.Context, w http.ResponseWriter, re
return
}
defer stream.Close()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(sseWriter{w: w})
flush := func() {
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
enc, flush := sseResponse(w)
taskID := uuid.New().String()
contextID := p.Message.ContextID
if contextID == "" {
contextID = uuid.New().String()
}
// One artifact id for the whole stream so append:true chunks target it.
artifactID := uuid.New().String()
// Open with the Task snapshot (working) so the client learns the ids.
initial := taskFromReplyWithIDs(p.Message, "", stateWorking, taskID, contextID)
d.store(initial)
writeSSE(enc, flush, req.ID, initial)
var reply strings.Builder
for {
chunk, err := stream.Recv()
if err == io.EOF {
task := taskFromReplyWithIDs(p.Message, reply.String(), stateCompleted, taskID, contextID)
d.store(task)
_ = enc.Encode(rpcResponse{JSONRPC: "2.0", ID: req.ID, Result: task})
flush()
// Spec-shaped terminal: a status-update with final:true — not a
// full Task snapshot, which carries no terminal marker.
writeSSE(enc, flush, req.ID, statusUpdateEvent(task, true))
return
}
if err != nil {
task := taskFromReplyWithIDs(p.Message, "error: "+err.Error(), stateFailed, taskID, contextID)
d.store(task)
_ = enc.Encode(rpcResponse{JSONRPC: "2.0", ID: req.ID, Result: task, Error: &rpcError{Code: errInternal, Message: err.Error()}})
flush()
// A failed status-update (final) — never `result` and `error`
// together in one response, which strict clients reject.
writeSSE(enc, flush, req.ID, statusUpdateEvent(task, true))
return
}
if chunk == nil || chunk.Reply == "" {
continue
}
reply.WriteString(chunk.Reply)
task := taskFromReplyWithIDs(p.Message, reply.String(), stateWorking, taskID, contextID)
d.store(task)
_ = enc.Encode(rpcResponse{JSONRPC: "2.0", ID: req.ID, Result: task})
flush()
// Emit the delta as an append artifact-update; keep the stored task
// current for tasks/get and resubscribe watchers.
d.store(taskFromReplyWithIDs(p.Message, reply.String(), stateWorking, taskID, contextID))
writeSSE(enc, flush, req.ID, TaskArtifactUpdateEvent{
TaskID: taskID,
ContextID: contextID,
Kind: "artifact-update",
Artifact: Artifact{ArtifactID: artifactID, Parts: []Part{{Kind: "text", Text: chunk.Reply}}},
Append: true,
})
}
}
@@ -653,20 +782,16 @@ func (d *dispatcher) resubscribe(ctx context.Context, w http.ResponseWriter, req
}
defer unsubscribe()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(sseWriter{w: w})
flush := func() {
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
enc, flush := sseResponse(w)
writeEvent := func(t *Task) bool {
_ = enc.Encode(rpcResponse{JSONRPC: "2.0", ID: req.ID, Result: t})
flush()
return isTerminal(t.Status.State)
writeSSE(enc, flush, req.ID, t)
if isTerminal(t.Status.State) {
// Close the stream with a spec-shaped terminal marker so external
// clients see `final:true`.
writeSSE(enc, flush, req.ID, statusUpdateEvent(t, true))
return true
}
return false
}
if writeEvent(task) {
return
@@ -710,6 +835,11 @@ func (d *dispatcher) setPushConfig(w http.ResponseWriter, req rpcRequest) {
writeRPC(w, req.ID, nil, &rpcError{Code: errInvalidParams, Message: "invalid params"})
return
}
// Reject SSRF-unsafe callback targets before storing them.
if err := d.checkPushURL(p.PushNotificationConfig.URL); err != nil {
writeRPC(w, req.ID, nil, &rpcError{Code: errInvalidParams, Message: "push notification url not allowed"})
return
}
d.mu.Lock()
task := d.tasks[p.ID]
if task != nil {
@@ -765,6 +895,15 @@ func (g *Gateway) callAgent(ctx context.Context, name, message string) (string,
// ---------------------------------------------------------------------------
func (d *dispatcher) store(t *Task) {
// Verify any AP2 mandates carried on the task (opt-in) and surface the
// outcome so a downstream paid path can trust — or reject — the mandate.
if d.ap2Verify != nil && len(t.AP2Mandates) > 0 && len(t.AP2Verifications) == 0 {
v := make([]AP2Verification, 0, len(t.AP2Mandates))
for _, m := range t.AP2Mandates {
v = append(v, d.ap2Verify(m, *t))
}
t.AP2Verifications = v
}
d.mu.Lock()
_, exists := d.tasks[t.ID]
d.tasks[t.ID] = t
@@ -878,6 +1017,11 @@ func (d *dispatcher) deliverPush(taskID string, task *Task) {
if !ok || cfg.URL == "" || task == nil {
return
}
// Defense in depth: re-validate the callback URL at delivery time in case
// the policy tightened or the config was set before it applied.
if err := d.checkPushURL(cfg.URL); err != nil {
return
}
body, err := json.Marshal(task)
if err != nil {
return
@@ -892,7 +1036,7 @@ func (d *dispatcher) deliverPush(taskID string, task *Task) {
if cfg.Token != "" {
req.Header.Set("Authorization", "Bearer "+cfg.Token)
}
resp, err := http.DefaultClient.Do(req)
resp, err := d.pushClient().Do(req)
if err == nil && resp.Body != nil {
_ = resp.Body.Close()
}
@@ -1029,6 +1173,27 @@ func requestContext(parent context.Context) context.Context {
return ctx
}
// sseResponse writes the SSE response headers and returns an encoder and a
// flush func for emitting `data:`-framed JSON-RPC events.
func sseResponse(w http.ResponseWriter) (*json.Encoder, func()) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.WriteHeader(http.StatusOK)
enc := json.NewEncoder(sseWriter{w: w})
return enc, func() {
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
}
// writeSSE emits one JSON-RPC event (result only — never with an error) and flushes.
func writeSSE(enc *json.Encoder, flush func(), id json.RawMessage, result any) {
_ = enc.Encode(rpcResponse{JSONRPC: "2.0", ID: id, Result: result})
flush()
}
type sseWriter struct {
w http.ResponseWriter
}
+201 -100
View File
@@ -9,6 +9,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
@@ -99,6 +100,38 @@ func TestAgentCardFromRegistry(t *testing.T) {
}
}
// A2A 0.3.0 discovery is /.well-known/agent-card.json. The card must be
// reachable there (canonical) as well as at the legacy agent.json alias, both
// per-agent and at the single-agent top level.
func TestAgentCardCanonicalWellKnownPath(t *testing.T) {
ts, cleanup := newGatewayWithAgent(t)
defer cleanup()
for _, path := range []string{
"/agents/echo/.well-known/agent-card.json",
"/agents/echo/.well-known/agent.json",
"/agents/echo/skills/task/.well-known/agent-card.json",
} {
resp, err := http.Get(ts.URL + path)
if err != nil {
t.Fatalf("get %s: %v", path, err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
t.Fatalf("%s status = %d, want 200", path, resp.StatusCode)
}
var card AgentCard
if err := json.NewDecoder(resp.Body).Decode(&card); err != nil {
resp.Body.Close()
t.Fatalf("%s decode card: %v", path, err)
}
resp.Body.Close()
if card.Name != "echo" {
t.Errorf("%s card name = %q, want echo", path, card.Name)
}
}
}
func TestSkillEndpointServesFocusedCardAndRoutesRPC(t *testing.T) {
ts, cleanup := newGatewayWithAgent(t)
defer cleanup()
@@ -191,6 +224,10 @@ func TestMessageSendContinuesExistingTask(t *testing.T) {
func TestPushNotificationConfigDeliversTaskUpdates(t *testing.T) {
d := newDispatcher()
// The test receiver is a loopback httptest server; authorize it the way a
// deployment would authorize a trusted in-cluster push receiver.
d.allowPushURL = func(*url.URL) error { return nil }
d.guardPushDial = false
updates := make(chan Task, 2)
push := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Authorization"); got != "Bearer secret" {
@@ -335,6 +372,67 @@ func (s *sliceStream) Recv() (*ai.Response, error) {
func (s *sliceStream) Close() error { return nil }
// streamEvent is one decoded SSE JSON-RPC event from a message/stream response.
// A2A streams carry heterogeneous results (Task, status-update, artifact-update)
// discriminated by `kind`, so we keep the raw result and decode on demand.
type streamEvent struct {
Result json.RawMessage `json:"result"`
Error *rpcError `json:"error"`
}
func (e streamEvent) kind() string {
var k struct {
Kind string `json:"kind"`
}
_ = json.Unmarshal(e.Result, &k)
return k.Kind
}
func (e streamEvent) task(t *testing.T) Task {
t.Helper()
var task Task
if err := json.Unmarshal(e.Result, &task); err != nil {
t.Fatalf("decode task event: %v", err)
}
return task
}
func (e streamEvent) status(t *testing.T) TaskStatusUpdateEvent {
t.Helper()
var s TaskStatusUpdateEvent
if err := json.Unmarshal(e.Result, &s); err != nil {
t.Fatalf("decode status-update event: %v", err)
}
return s
}
func (e streamEvent) artifactUpdate(t *testing.T) TaskArtifactUpdateEvent {
t.Helper()
var a TaskArtifactUpdateEvent
if err := json.Unmarshal(e.Result, &a); err != nil {
t.Fatalf("decode artifact-update event: %v", err)
}
return a
}
// collectSSE parses the `data:`-framed JSON-RPC events from an SSE body.
func collectSSE(t *testing.T, body string) []streamEvent {
t.Helper()
var events []streamEvent
for _, line := range strings.Split(strings.TrimSpace(body), "\n") {
line = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "data:"))
if line == "" {
continue
}
var e streamEvent
if err := json.Unmarshal([]byte(line), &e); err != nil {
t.Fatalf("decode event %q: %v", line, err)
}
events = append(events, e)
}
return events
}
func TestMessageStreamChunksStoreFinalTask(t *testing.T) {
d := newDispatcher()
body := `{"jsonrpc":"2.0","id":1,"method":"message/stream","params":{"message":{"role":"user","parts":[{"kind":"text","text":"ping"}],"kind":"message"}}}`
@@ -351,47 +449,61 @@ func TestMessageStreamChunksStoreFinalTask(t *testing.T) {
if ct := rr.Result().Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/event-stream") {
t.Fatalf("content-type = %q, want text/event-stream", ct)
}
var events []struct {
Result Task `json:"result"`
Error *rpcError `json:"error"`
events := collectSSE(t, rr.Body.String())
// Opening Task snapshot + one append artifact-update per chunk + terminal
// status-update.
if len(events) != 4 {
t.Fatalf("events = %d, want 4; body %s", len(events), rr.Body.String())
}
for _, line := range strings.Split(strings.TrimSpace(rr.Body.String()), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
line = strings.TrimPrefix(line, "data: ")
var event struct {
Result Task `json:"result"`
Error *rpcError `json:"error"`
}
if err := json.Unmarshal([]byte(line), &event); err != nil {
t.Fatalf("decode event %q: %v", line, err)
}
events = append(events, event)
}
if len(events) != 3 {
t.Fatalf("events = %d, want 3; body %s", len(events), rr.Body.String())
}
for i, event := range events {
if event.Error != nil {
t.Fatalf("event %d error: %+v", i, event.Error)
}
if event.Result.ID != events[0].Result.ID || event.Result.ContextID != events[0].Result.ContextID {
t.Fatalf("event %d changed task identity: %+v vs %+v", i, event.Result, events[0].Result)
for i, e := range events {
if e.Error != nil {
t.Fatalf("event %d carried an error field: %+v", i, e.Error)
}
}
if events[0].Result.Status.State != stateWorking || textOf(events[0].Result.Artifacts[0].Parts) != "po" {
t.Fatalf("first event = %+v, want working po", events[0].Result)
if events[0].kind() != "task" {
t.Fatalf("first event kind = %q, want task", events[0].kind())
}
final := events[len(events)-1].Result
if final.Status.State != stateCompleted || textOf(final.Artifacts[0].Parts) != "pong" {
t.Fatalf("final event = %+v, want completed pong", final)
opening := events[0].task(t)
if opening.Status.State != stateWorking {
t.Fatalf("opening task state = %q, want working", opening.Status.State)
}
taskID := opening.ID
// The middle events are append artifact-updates carrying the chunk deltas.
var text strings.Builder
for _, e := range events[1:3] {
if e.kind() != "artifact-update" {
t.Fatalf("event kind = %q, want artifact-update", e.kind())
}
au := e.artifactUpdate(t)
if !au.Append {
t.Fatalf("artifact-update should be append: %+v", au)
}
if au.TaskID != taskID {
t.Fatalf("artifact-update taskId = %q, want %q", au.TaskID, taskID)
}
text.WriteString(textOf(au.Artifact.Parts))
}
if text.String() != "pong" {
t.Fatalf("accumulated artifact text = %q, want pong", text.String())
}
got := rpcTaskFromDispatcher(t, d, final.ID)
if got.ID != final.ID || got.Status.State != stateCompleted || textOf(got.Artifacts[0].Parts) != "pong" {
t.Fatalf("stored task = %+v, want final", got)
// The stream closes with a terminal status-update (final:true).
last := events[len(events)-1]
if last.kind() != "status-update" {
t.Fatalf("last event kind = %q, want status-update", last.kind())
}
su := last.status(t)
if !su.Final || su.Status.State != stateCompleted {
t.Fatalf("terminal event = %+v, want final completed", su)
}
if su.TaskID != taskID {
t.Fatalf("terminal taskId = %q, want %q", su.TaskID, taskID)
}
got := rpcTaskFromDispatcher(t, d, taskID)
if got.ID != taskID || got.Status.State != stateCompleted || textOf(got.Artifacts[0].Parts) != "pong" {
t.Fatalf("stored task = %+v, want final completed pong", got)
}
}
@@ -432,37 +544,31 @@ func TestMessageStreamChunksPropagatesCancellationAndClosesStream(t *testing.T)
t.Fatal("stream was not closed")
}
var events []struct {
Result Task `json:"result"`
Error *rpcError `json:"error"`
events := collectSSE(t, rr.Body.String())
// Opening Task snapshot, then a terminal failed status-update.
if len(events) != 2 {
t.Fatalf("events = %d, want 2; body %s", len(events), rr.Body.String())
}
for _, line := range strings.Split(strings.TrimSpace(rr.Body.String()), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
// A streaming failure must be a failed status-update, never `result` and
// `error` set together in one response.
for i, e := range events {
if e.Error != nil {
t.Fatalf("event %d carried an error field (result+error not allowed): %+v", i, e.Error)
}
line = strings.TrimPrefix(line, "data: ")
var event struct {
Result Task `json:"result"`
Error *rpcError `json:"error"`
}
if err := json.Unmarshal([]byte(line), &event); err != nil {
t.Fatalf("decode event %q: %v", line, err)
}
events = append(events, event)
}
if len(events) != 1 {
t.Fatalf("events = %d, want 1; body %s", len(events), rr.Body.String())
if events[0].kind() != "task" || events[0].task(t).Status.State != stateWorking {
t.Fatalf("first event = %s, want working task", string(events[0].Result))
}
event := events[0]
if event.Error == nil || event.Error.Code != errInternal || event.Error.Message != context.Canceled.Error() {
t.Fatalf("error = %+v, want context cancellation", event.Error)
last := events[1]
if last.kind() != "status-update" {
t.Fatalf("last event kind = %q, want status-update", last.kind())
}
if event.Result.Status.State != stateFailed || textOf(event.Result.Artifacts[0].Parts) != "error: context canceled" {
t.Fatalf("failed task = %+v, want context cancellation artifact", event.Result)
su := last.status(t)
if !su.Final || su.Status.State != stateFailed {
t.Fatalf("terminal event = %+v, want final failed", su)
}
got := rpcTaskFromDispatcher(t, d, event.Result.ID)
got := rpcTaskFromDispatcher(t, d, su.TaskID)
if got.Status.State != stateFailed || textOf(got.Artifacts[0].Parts) != "error: context canceled" {
t.Fatalf("stored task = %+v, want failed cancellation", got)
}
@@ -493,33 +599,24 @@ func TestMessageStreamChunksFallsBackWhenUnsupported(t *testing.T) {
if ct := rr.Result().Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/event-stream") {
t.Fatalf("content-type = %q, want text/event-stream", ct)
}
var events []struct {
Result Task `json:"result"`
Error *rpcError `json:"error"`
events := collectSSE(t, rr.Body.String())
// The non-streaming fallback emits a completed Task snapshot then a terminal
// status-update.
if len(events) != 2 {
t.Fatalf("events = %d, want 2; body %s", len(events), rr.Body.String())
}
for _, line := range strings.Split(strings.TrimSpace(rr.Body.String()), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
for i, e := range events {
if e.Error != nil {
t.Fatalf("fallback event %d error: %+v", i, e.Error)
}
line = strings.TrimPrefix(line, "data: ")
var event struct {
Result Task `json:"result"`
Error *rpcError `json:"error"`
}
if err := json.Unmarshal([]byte(line), &event); err != nil {
t.Fatalf("decode event %q: %v", line, err)
}
events = append(events, event)
}
if len(events) != 1 {
t.Fatalf("events = %d, want 1; body %s", len(events), rr.Body.String())
task := events[0].task(t)
if task.Status.State != stateCompleted || textOf(task.Artifacts[0].Parts) != "pong" {
t.Fatalf("fallback task = %+v, want completed pong", task)
}
if events[0].Error != nil {
t.Fatalf("fallback event error: %+v", events[0].Error)
}
if events[0].Result.Status.State != stateCompleted || textOf(events[0].Result.Artifacts[0].Parts) != "pong" {
t.Fatalf("fallback task = %+v, want completed pong", events[0].Result)
su := events[1].status(t)
if !su.Final || su.Status.State != stateCompleted {
t.Fatalf("terminal event = %+v, want final completed", su)
}
}
@@ -535,30 +632,34 @@ func TestMessageStreamFallbackDoesNotCompleteWithEmptyText(t *testing.T) {
return nil, fmt.Errorf("%w: test provider", ai.ErrStreamingUnsupported)
})
var event struct {
Result Task `json:"result"`
Error *rpcError `json:"error"`
}
for _, line := range strings.Split(strings.TrimSpace(rr.Body.String()), "\n") {
line = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), "data: "))
if line == "" {
continue
events := collectSSE(t, rr.Body.String())
var task Task
var foundTask bool
for _, e := range events {
if e.Error != nil {
t.Fatalf("fallback event error: %+v", e.Error)
}
if err := json.Unmarshal([]byte(line), &event); err != nil {
t.Fatalf("decode event %q: %v", line, err)
if e.kind() == "task" {
task = e.task(t)
foundTask = true
}
}
if event.Error != nil {
t.Fatalf("fallback event error: %+v", event.Error)
if !foundTask {
t.Fatalf("no task event in stream; body %s", rr.Body.String())
}
if event.Result.Status.State != stateFailed {
t.Fatalf("fallback state = %q, want failed", event.Result.Status.State)
if task.Status.State != stateFailed {
t.Fatalf("fallback state = %q, want failed", task.Status.State)
}
if got := textOf(event.Result.Artifacts[0].Parts); got == "" {
t.Fatalf("fallback artifact text is empty: %+v", event.Result.Artifacts)
if got := textOf(task.Artifacts[0].Parts); got == "" {
t.Fatalf("fallback artifact text is empty: %+v", task.Artifacts)
}
if got := textOf(event.Result.History[len(event.Result.History)-1].Parts); got == "" {
t.Fatalf("fallback history text is empty: %+v", event.Result.History)
if got := textOf(task.History[len(task.History)-1].Parts); got == "" {
t.Fatalf("fallback history text is empty: %+v", task.History)
}
// The stream still ends with a terminal marker.
last := events[len(events)-1]
if last.kind() != "status-update" || !last.status(t).Final {
t.Fatalf("stream must end with a final status-update; got %s", string(last.Result))
}
}
+80
View File
@@ -1,7 +1,10 @@
package a2a
import (
"context"
"crypto/ed25519"
"encoding/json"
"fmt"
"strings"
"testing"
"time"
@@ -50,6 +53,83 @@ func TestAP2PaymentMandateX402RailReference(t *testing.T) {
}
}
// TestAP2GatewayVerifiesInboundPaymentMandate drives a real A2A message/send
// carrying a signed x402 payment mandate through the gateway and asserts the
// mandate is verified (and the x402 rail carried) into the task a paid path
// consults — and that a tampered mandate is surfaced as unverified.
func TestAP2GatewayVerifiesInboundPaymentMandate(t *testing.T) {
pub, priv := testAP2Key(t)
d := newDispatcher()
d.ap2Verify = func(s AP2SignedMandate, task Task) AP2Verification {
return VerifyAP2ForTask(s, pub, task, nil)
}
invoke := func(context.Context, string) (string, error) { return "fetched", nil }
send := func(t *testing.T, mandate AP2SignedMandate) Task {
t.Helper()
msg := AP2AttachMandate(
Message{Role: "user", Kind: "message", MessageID: "m1", Parts: []Part{{Kind: "text", Text: "pay and fetch"}}},
mandate,
)
params, err := json.Marshal(sendParams{Message: msg})
if err != nil {
t.Fatal(err)
}
body := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"message/send","params":%s}`, params)
return rpcTaskFromBody(t, d, body, invoke)
}
rail := X402AP2Rail("payreq_777")
good, err := SignAP2Mandate(AP2Mandate{ID: "pay-1", Kind: AP2PaymentMandate, Rail: &rail, IssuedAt: time.Unix(1, 0).UTC()}, "k", priv)
if err != nil {
t.Fatal(err)
}
task := send(t, good)
if len(task.AP2Verifications) != 1 || !task.AP2Verifications[0].Verified {
t.Fatalf("inbound payment mandate not verified: %+v", task.AP2Verifications)
}
if task.AP2Verifications[0].Kind != string(AP2PaymentMandate) {
t.Errorf("verification kind = %q, want payment", task.AP2Verifications[0].Kind)
}
if len(task.AP2Mandates) != 1 || task.AP2Mandates[0].Mandate.Rail == nil ||
task.AP2Mandates[0].Mandate.Rail.Type != "x402" || task.AP2Mandates[0].Mandate.Rail.Reference != "payreq_777" {
t.Fatalf("x402 settlement rail not carried onto task: %+v", task.AP2Mandates)
}
tampered := good
tampered.Mandate.Amount = "999.00"
bad := send(t, tampered)
if len(bad.AP2Verifications) != 1 || bad.AP2Verifications[0].Verified {
t.Fatalf("tampered mandate should be unverified: %+v", bad.AP2Verifications)
}
if !strings.Contains(bad.AP2Verifications[0].Error, "signature") {
t.Errorf("tampered verification error = %q, want signature failure", bad.AP2Verifications[0].Error)
}
}
// TestAP2CarriedUnverifiedWithoutKey confirms the default (no configured key)
// is unchanged: mandates are carried but not verified.
func TestAP2CarriedUnverifiedWithoutKey(t *testing.T) {
_, priv := testAP2Key(t)
d := newDispatcher() // no ap2Verify configured
rail := X402AP2Rail("payreq_1")
signed, err := SignAP2Mandate(AP2Mandate{ID: "pay-1", Kind: AP2PaymentMandate, Rail: &rail, IssuedAt: time.Unix(1, 0).UTC()}, "k", priv)
if err != nil {
t.Fatal(err)
}
msg := AP2AttachMandate(Message{Role: "user", Kind: "message", MessageID: "m1", Parts: []Part{{Kind: "text", Text: "x"}}}, signed)
params, _ := json.Marshal(sendParams{Message: msg})
body := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"message/send","params":%s}`, params)
task := rpcTaskFromBody(t, d, body, func(context.Context, string) (string, error) { return "ok", nil })
if len(task.AP2Mandates) != 1 {
t.Fatalf("mandate should still be carried: %+v", task.AP2Mandates)
}
if len(task.AP2Verifications) != 0 {
t.Errorf("no verifications without a configured key, got %+v", task.AP2Verifications)
}
}
func TestAP2TamperCasesFailDistinctly(t *testing.T) {
pub, priv := testAP2Key(t)
rail := X402AP2Rail("payreq_123")
+4 -1
View File
@@ -6,6 +6,7 @@ import (
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
@@ -56,9 +57,11 @@ func TestClientSendAndCard(t *testing.T) {
func TestClientContinuesTaskAndConfiguresPush(t *testing.T) {
card := Card("solo", "http://localhost:4000", "", []string{"task"})
// The push receiver below is a loopback test server; authorize it as a
// deployment would authorize its trusted push receiver.
h := NewAgentHandler(card, func(_ context.Context, text string) (string, error) {
return "echo:" + text, nil
})
}, WithPushURLPolicy(func(*url.URL) error { return nil }))
ts := httptest.NewServer(h)
defer ts.Close()
+131
View File
@@ -0,0 +1,131 @@
package a2a
import (
"fmt"
"net"
"net/http"
"net/url"
"syscall"
"time"
)
// Push-notification callbacks are the one place the A2A gateway makes an
// outbound HTTP request to an address chosen by a (possibly untrusted) caller:
// tasks/pushNotificationConfig/set records a URL and deliverPush POSTs task
// state to it. Without a guard that is a server-side request forgery vector —
// a caller can aim the gateway at loopback, link-local (cloud metadata), or
// private hosts it would otherwise never reach.
//
// The default policy allows only http/https callbacks whose host does not
// resolve to a loopback, private, link-local, or unspecified address, and the
// guarded HTTP client re-checks the *resolved* IP at dial time so a hostname
// that passes validation cannot be rebound to an internal address before the
// connection is made. Operators who need to reach a trusted in-cluster
// receiver set Options.AllowPushURL to take over the policy.
// pushLookupIP resolves a host to IPs; overridable in tests.
var pushLookupIP = net.LookupIP
// defaultPushURLPolicy is the SSRF-safe policy applied when no AllowPushURL is
// configured. It rejects non-http(s) schemes and hosts that resolve to a
// loopback, private, link-local, multicast, or unspecified address.
func defaultPushURLPolicy(u *url.URL) error {
switch u.Scheme {
case "http", "https":
default:
return fmt.Errorf("push callback scheme %q not allowed (want http or https)", u.Scheme)
}
host := u.Hostname()
if host == "" {
return fmt.Errorf("push callback url has no host")
}
ips, err := resolvePushHost(host)
if err != nil {
return fmt.Errorf("push callback host %q: %w", host, err)
}
if len(ips) == 0 {
return fmt.Errorf("push callback host %q did not resolve", host)
}
for _, ip := range ips {
if blockedPushIP(ip) {
return fmt.Errorf("push callback host %q resolves to a blocked address %s", host, ip)
}
}
return nil
}
func resolvePushHost(host string) ([]net.IP, error) {
if ip := net.ParseIP(host); ip != nil {
return []net.IP{ip}, nil
}
return pushLookupIP(host)
}
// blockedPushIP reports whether ip is one an outbound push callback must not
// reach: loopback, private (RFC1918 / ULA), link-local (incl. 169.254.169.254
// cloud metadata), multicast, or the unspecified address.
func blockedPushIP(ip net.IP) bool {
return ip == nil ||
ip.IsLoopback() ||
ip.IsPrivate() ||
ip.IsLinkLocalUnicast() ||
ip.IsLinkLocalMulticast() ||
ip.IsInterfaceLocalMulticast() ||
ip.IsMulticast() ||
ip.IsUnspecified()
}
// pushDialControl runs after DNS resolution, immediately before connect, on the
// resolved address — so it blocks a host that passed URL validation but was
// rebound to an internal IP (DNS rebinding).
func pushDialControl(_, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
ip := net.ParseIP(host)
if ip == nil {
return fmt.Errorf("push callback: cannot parse dial address %q", address)
}
if blockedPushIP(ip) {
return fmt.Errorf("push callback: refusing to connect to blocked address %s", ip)
}
return nil
}
// pushGuardClient is the HTTP client used for default-policy push delivery. Its
// dialer refuses connections to blocked addresses at connect time.
var pushGuardClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
Control: pushDialControl,
}).DialContext,
},
}
// checkPushURL validates a callback URL against the dispatcher's effective
// policy (Options.AllowPushURL, or the default SSRF-safe policy).
func (d *dispatcher) checkPushURL(raw string) error {
u, err := url.Parse(raw)
if err != nil {
return fmt.Errorf("invalid push callback url: %w", err)
}
policy := d.allowPushURL
if policy == nil {
policy = defaultPushURLPolicy
}
return policy(u)
}
// pushClient is the HTTP client deliverPush uses: the guarded client under the
// default policy, or the default client when an operator has taken over the
// policy via Options.AllowPushURL (they own the trust decision then).
func (d *dispatcher) pushClient() *http.Client {
if d.guardPushDial {
return pushGuardClient
}
return http.DefaultClient
}
+147
View File
@@ -0,0 +1,147 @@
package a2a
import (
"encoding/json"
"net"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
func TestDefaultPushURLPolicy(t *testing.T) {
// Resolve test hostnames deterministically without real DNS.
orig := pushLookupIP
pushLookupIP = func(host string) ([]net.IP, error) {
switch host {
case "internal.example":
return []net.IP{net.ParseIP("10.1.2.3")}, nil
case "public.example":
return []net.IP{net.ParseIP("93.184.216.34")}, nil
case "rebind.example":
// A host that resolves to both a public and an internal IP must be
// rejected — any blocked address is disqualifying.
return []net.IP{net.ParseIP("93.184.216.34"), net.ParseIP("127.0.0.1")}, nil
}
return nil, &net.DNSError{Err: "no such host", Name: host, IsNotFound: true}
}
defer func() { pushLookupIP = orig }()
blocked := []string{
"http://127.0.0.1/hook", // loopback
"http://169.254.169.254/latest/meta", // cloud metadata (link-local)
"http://10.0.0.5/hook", // RFC1918
"http://[::1]/hook", // IPv6 loopback
"http://[fd00::1]/hook", // IPv6 ULA (private)
"http://0.0.0.0/hook", // unspecified
"http://internal.example/hook", // hostname → private
"http://rebind.example/hook", // one internal IP among many
"ftp://public.example/hook", // non-http(s) scheme
"file:///etc/passwd", // scheme
"http:///nohost", // no host
}
for _, raw := range blocked {
u, err := url.Parse(raw)
if err != nil {
t.Fatalf("parse %q: %v", raw, err)
}
if err := defaultPushURLPolicy(u); err == nil {
t.Errorf("defaultPushURLPolicy(%q) = nil, want blocked", raw)
}
}
allowed := []string{
"http://93.184.216.34/hook", // public literal IP
"https://public.example/hook", // hostname → public
}
for _, raw := range allowed {
u, _ := url.Parse(raw)
if err := defaultPushURLPolicy(u); err != nil {
t.Errorf("defaultPushURLPolicy(%q) = %v, want allowed", raw, err)
}
}
}
func TestPushDialControlBlocksPrivate(t *testing.T) {
blocked := []string{"127.0.0.1:80", "169.254.169.254:80", "10.0.0.1:443", "[::1]:80", "0.0.0.0:80"}
for _, addr := range blocked {
if err := pushDialControl("tcp", addr, nil); err == nil {
t.Errorf("pushDialControl(%q) = nil, want blocked", addr)
}
}
if err := pushDialControl("tcp", "8.8.8.8:443", nil); err != nil {
t.Errorf("pushDialControl(public) = %v, want allowed", err)
}
}
// TestSetPushConfigRejectsSSRFURL: an untrusted caller cannot register a
// callback pointing at an internal address — it is refused and nothing stored.
func TestSetPushConfigRejectsSSRFURL(t *testing.T) {
d := newDispatcher()
d.store(&Task{ID: "t1", ContextID: "c1", Status: TaskStatus{State: stateCompleted}})
params, _ := json.Marshal(map[string]any{
"id": "t1",
"pushNotificationConfig": map[string]any{"url": "http://169.254.169.254/latest/meta-data"},
})
rr := httptest.NewRecorder()
d.setPushConfig(rr, rpcRequest{JSONRPC: "2.0", ID: json.RawMessage("1"), Params: params})
var resp rpcResponse
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp.Error == nil || resp.Error.Code != errInvalidParams {
t.Fatalf("response = %+v, want invalid-params rejection", resp)
}
d.mu.Lock()
_, stored := d.pushConfigs["t1"]
d.mu.Unlock()
if stored {
t.Error("SSRF callback url must not be stored")
}
}
// TestDeliverPushBlocksInternalByDefault: even if a config for an internal URL
// slips into the map, deliverPush must not POST to it under the default policy.
func TestDeliverPushBlocksInternalByDefault(t *testing.T) {
var hit bool
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hit = true }))
defer srv.Close() // srv.URL is http://127.0.0.1:PORT — loopback, must be blocked
d := newDispatcher()
task := &Task{ID: "t1", Status: TaskStatus{State: stateCompleted}}
d.pushConfigs["t1"] = PushNotificationConfig{URL: srv.URL}
d.deliverPush("t1", task)
if hit {
t.Error("deliverPush reached a loopback callback under the default policy")
}
}
// TestAllowPushURLOverrideDelivers: an operator policy can authorize a trusted
// (here loopback) receiver, and delivery then goes through.
func TestAllowPushURLOverrideDelivers(t *testing.T) {
done := make(chan struct{}, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") == "application/json" {
done <- struct{}{}
}
}))
defer srv.Close()
g := New(Options{AllowPushURL: func(*url.URL) error { return nil }})
d := g.disp
if d.guardPushDial {
t.Fatal("custom AllowPushURL should disable the dial guard")
}
task := &Task{ID: "t1", Status: TaskStatus{State: stateCompleted}}
d.pushConfigs["t1"] = PushNotificationConfig{URL: srv.URL}
d.deliverPush("t1", task)
select {
case <-done:
default:
t.Error("operator-authorized callback was not delivered")
}
}
+13 -10
View File
@@ -47,13 +47,23 @@ func main() {
}
```
### Gateway with MCP
### Run the MCP gateway alongside
The HTTP API gateway no longer starts MCP. Run the MCP gateway independently
so each has its own lifecycle:
```go
mcpSrv, err := mcp.NewServer(mcp.Options{
Address: ":3000",
Registry: registry.DefaultRegistry,
})
if err != nil {
panic(err)
}
go mcpSrv.Serve()
gw, err := api.New(api.Options{
Address: ":8080",
MCPEnabled: true,
MCPAddress: ":3000", // MCP on separate port
HandlerRegistrar: registerHandlers,
})
```
@@ -101,12 +111,6 @@ type Options struct {
// HandlerRegistrar registers HTTP handlers on the mux
HandlerRegistrar func(mux *http.ServeMux) error
// MCPEnabled enables the MCP gateway
MCPEnabled bool
// MCPAddress is the address for MCP gateway (e.g., ":3000")
MCPAddress string
// Registry for service discovery (default: registry.DefaultRegistry)
Registry registry.Registry
}
@@ -121,7 +125,6 @@ type Options struct {
│ │ Gateway │ │
│ │ - Manages HTTP server │ │
│ │ - Calls HandlerRegistrar │ │
│ │ - Starts MCP if enabled │ │
│ └────────────────────────────────────┘ │
└─────────────────────────────────────────┘
↓ delegates to
-21
View File
@@ -12,7 +12,6 @@ import (
"net/http"
"time"
"go-micro.dev/v6/gateway/mcp"
"go-micro.dev/v6/registry"
)
@@ -35,12 +34,6 @@ type Options struct {
// This allows different configurations (dev vs prod) to register different handlers
HandlerRegistrar func(mux *http.ServeMux) error
// MCPEnabled controls whether to start MCP gateway
MCPEnabled bool
// MCPAddress is the address for MCP gateway (e.g., ":3000")
MCPAddress string
// Registry for service discovery (if nil, uses registry.DefaultRegistry)
Registry registry.Registry
}
@@ -92,20 +85,6 @@ func New(opts Options) (*Gateway, error) {
mux: mux,
}
// Start MCP gateway if enabled
if opts.MCPEnabled && opts.MCPAddress != "" {
go func() {
if err := mcp.ListenAndServe(opts.MCPAddress, mcp.Options{
Registry: opts.Registry,
Context: opts.Context,
Logger: opts.Logger,
}); err != nil {
opts.Logger.Printf("[mcp] MCP gateway error: %v", err)
}
}()
opts.Logger.Printf("[mcp] MCP gateway enabled on %s", opts.MCPAddress)
}
// Start server in background
go func() {
opts.Logger.Printf("[gateway] Listening on %s (auth: %v)", opts.Address, opts.AuthEnabled)
@@ -15,7 +15,7 @@ helm install mcp-gateway ./deploy/helm/mcp-gateway \
| Parameter | Description | Default |
|-----------|-------------|---------|
| `replicaCount` | Number of gateway replicas | `1` |
| `image.repository` | Container image | `ghcr.io/micro/mcp-gateway` |
| `image.repository` | Container image | `ghcr.io/micro/go-micro` |
| `image.tag` | Image tag (defaults to appVersion) | `""` |
| `gateway.address` | Listen address | `:3000` |
| `gateway.registry` | Registry backend (mdns, consul, etcd) | `consul` |
@@ -41,14 +41,9 @@ spec:
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
args:
- "--address"
- "gateway"
- "--mcp-address"
- {{ .Values.gateway.address | quote }}
- "--registry"
- {{ .Values.gateway.registry | quote }}
{{- if .Values.gateway.registryAddress }}
- "--registry-address"
- {{ .Values.gateway.registryAddress | quote }}
{{- end }}
{{- if gt (float64 .Values.gateway.rateLimit) 0.0 }}
- "--rate-limit"
- {{ .Values.gateway.rateLimit | quote }}
@@ -65,6 +60,15 @@ spec:
- "--scope"
- {{ . | quote }}
{{- end }}
# Registry selection uses the micro CLI's global flags, which are
# read from the environment (they must precede the subcommand).
env:
- name: MICRO_REGISTRY
value: {{ .Values.gateway.registry | quote }}
{{- if .Values.gateway.registryAddress }}
- name: MICRO_REGISTRY_ADDRESS
value: {{ .Values.gateway.registryAddress | quote }}
{{- end }}
ports:
- name: http
containerPort: {{ trimPrefix ":" .Values.gateway.address | default "3000" }}

Some files were not shown because too many files have changed in this diff Show More