blaze

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 12 Imported by: 0

README

Blaze

CI Go Report Card Go Reference

Write a Go function once, expose it safely to OpenAI, Anthropic and MCP.

Why

Every LLM app with tools ends up writing the same glue: a JSON Schema per provider, a loop that turns the model's tool calls into function calls, and the defensive code around them. That defensive part is the one that tends to get skipped. Model output is untrusted input: arguments can be malformed, a call can hang, a handler can panic, a fetch tool can be pointed at 169.254.169.254.

Blaze is a small, zero-dependency Go toolkit for that layer. You register plain Go functions once. Blaze gives you the OpenAI and Anthropic tool definitions, converts the model's calls, validates arguments against the schema, and runs each call with timeouts, size limits and panic recovery. The same tools can be served to Claude Desktop, Claude Code or Cursor as an MCP server. Blaze never talks to the model itself: your app keeps its client, conversation and auth.

Quickstart

go get github.com/dvictor357/blaze
weather := adapter.NewTool("get_weather", "Current weather for a city", map[string]any{
    "type":       "object",
    "properties": map[string]any{"city": map[string]any{"type": "string"}},
    "required":   []string{"city"},
}, func(ctx context.Context, in json.RawMessage) (any, error) {
    var args struct{ City string `json:"city"` }
    if err := json.Unmarshal(in, &args); err != nil {
        return nil, err
    }
    return map[string]any{"city": args.City, "temp_c": 21}, nil
})
ex, err := adapter.NewExecutor(adapter.Config{}, weather)

def := ex.Tools()[0].ToAnthropic()             // or .ToOpenAI(): send it to your model
calls, err := adapter.AnthropicCalls(content)  // the model's tool_use blocks
results, err := ex.Execute(ctx, calls)         // validated, bounded, panic-safe
reply, err := adapter.AnthropicToolResultMessage(results)

The same ex serves MCP: blazemcp.ServeStdio(ctx, ex, blazemcp.Options{}). Full round trips are in examples/agent-loop.

Features

  • One definition, three targets. ToOpenAI(), ToAnthropic(), and an MCP server over stdio or Streamable HTTP, from the same adapter.Tool.
  • Runtime argument validation. Arguments are checked against the tool's JSON Schema before the handler runs. Violations come back as a tool error the model can read and fix: $.units: must be one of ["metric","imperial"], got "kelvin". Details.
  • Bounded execution. Per-call and per-batch timeouts, input/output size limits, whole-batch validation before anything runs, and panics turned into structured errors.
  • Safe built-in tools. web_fetch, web_read and web_search refuse private, loopback and metadata addresses (with DNS-rebinding protection); memory is scoped per user by your server, never by the model; plus datetime and json_query.
  • Provider conversions, not a provider client. Pure functions between Blaze and the OpenAI/Anthropic wire shapes. Use the official SDKs or raw HTTP; Blaze stays out of the conversation.
  • HTTP endpoint included. adapter.InvokeHandler and adapter.ListToolsHandler expose the executor as JSON or SSE, on a tiny net/http-based router.
  • Zero dependencies. The core module uses only the standard library. MCP lives in its own module (github.com/dvictor357/blaze/mcp) on top of the official MCP Go SDK.

Requires Go 1.25.5 or later.

Use it with MCP clients

cd examples/mcp-server && go build -o blaze-mcp .
claude mcp add blaze -- "$PWD/blaze-mcp"        # Claude Code

Claude Desktop and Cursor take the same binary:

{ "mcpServers": { "blaze": { "command": "/path/to/blaze-mcp" } } }

Streamable HTTP with bearer auth, per-user memory scopes and the full set of client configs: examples/mcp-server.

Examples

Example What it shows
examples/agent-loop Full model round trip with OpenAI and Anthropic using the built-in tools. Reads OPENAI_API_KEY / ANTHROPIC_API_KEY, skips a provider without one.
examples/mcp-server The tools as an MCP server for Claude Desktop, Claude Code and Cursor (stdio or HTTP).
examples/main.go An HTTP tool server: GET /v1/tools, POST /v1/invoke, bearer auth, SSE streaming.
OPENAI_API_KEY=... ANTHROPIC_API_KEY=... go run ./examples/agent-loop
BLAZE_TOKEN=dev go run ./examples     # then: curl -H 'Authorization: Bearer dev' 127.0.0.1:8080/v1/tools

Built-in tools

Tool Notes
web_fetch, web_read, web_search Shared tool.WebClient; validated DNS and redirects; private destinations blocked by default; bounded responses
memory Key-value, counters, lists, TTL; explicit store ownership; scope from tool.WithMemoryScope, never from tool input
datetime Current time, parsing, formatting, differences, durations
json_query Small path/filter language for extracting data from JSON

Documentation

The root package blaze is a small HTTP toolkit on net/http.ServeMux (groups, middleware, CORS, JSON binding with limits, NDJSON and SSE). See the package docs.

Status

v0.x: the API may still change between minor versions; changes are listed in the changelog. Issues and pull requests are welcome.

License

MIT.


Need help wiring this into your backend? Reach out: https://x.com/dvictor3579

Documentation

Index

Constants

View Source
const (
	DefaultReadHeaderTimeout = 5 * time.Second
	DefaultReadTimeout       = 30 * time.Second
	DefaultWriteTimeout      = 60 * time.Second
	DefaultIdleTimeout       = 120 * time.Second
	DefaultMaxHeaderBytes    = 64 << 10
)

Default server timeouts applied by Engine.Server and Engine.Listen. Handlers that legitimately run longer (streaming, long tool batches) extend their own write deadline with Context.SetWriteDeadline.

View Source
const DefaultMaxBodyBytes int64 = 1 << 20

DefaultMaxBodyBytes is the request body limit applied by BindJSON.

View Source
const StreamWriteTimeout = 10 * time.Second

StreamWriteTimeout bounds each individual write of a stream, so a client that stops reading cannot hold the handler forever. It also replaces the server-wide WriteTimeout for the lifetime of the stream.

Variables

This section is empty.

Functions

This section is empty.

Types

type CORSConfig

type CORSConfig struct {
	AllowOrigins []string
	AllowMethods []string
	AllowHeaders []string
	// MaxAge is how long browsers may cache a preflight answer (0 = unset).
	MaxAge time.Duration
}

CORSConfig defines CORS options

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig provides defaults that allow any origin. Restrict AllowOrigins for anything that is not a public API.

type Context

type Context struct {
	ResponseWriter http.ResponseWriter
	Request        *http.Request
	// contains filtered or unexported fields
}

Context wraps the request and response for convenient access

func (*Context) BindJSON

func (c *Context) BindJSON(v any) error

BindJSON decodes a single JSON value from the request body, limited to DefaultMaxBodyBytes. Failures are *HTTPError (413 or 400).

func (*Context) BindJSONLimit

func (c *Context) BindJSONLimit(v any, limit int64) error

BindJSONLimit is BindJSON with an explicit body size limit in bytes.

func (*Context) BindJSONStrict

func (c *Context) BindJSONStrict(v any, limit int64) error

BindJSONStrict is BindJSONLimit that also rejects unknown object fields.

func (*Context) HTML

func (c *Context) HTML(code int, html string) error

HTML sends an HTML response

func (*Context) JSON

func (c *Context) JSON(code int, data any) error

JSON sends a JSON response. The value is encoded before anything is written, so an unencodable value returns an error with the response still uncommitted.

func (*Context) NoContent

func (c *Context) NoContent() error

NoContent sends a 204 No Content response

func (*Context) Param

func (c *Context) Param(key string) string

Param returns a path parameter by its pattern name, unescaped.

func (*Context) Query

func (c *Context) Query(key string) string

Query returns a query parameter by key

func (*Context) QueryDefault

func (c *Context) QueryDefault(key, defaultVal string) string

QueryDefault returns a query parameter or a default value if not set

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

Redirect sends an HTTP redirect

func (*Context) SSE

func (c *Context) SSE() (*SSEWriter, error)

SSE starts a text/event-stream response and flushes the headers. It returns an error, with nothing committed, if the response writer cannot flush.

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader sets a response header

func (*Context) SetWriteDeadline

func (c *Context) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline of the underlying connection, for handlers that legitimately run longer than the server WriteTimeout. It returns an error wrapping http.ErrNotSupported when the server cannot.

func (*Context) StreamJSON

func (c *Context) StreamJSON(dataChan <-chan any) error

StreamJSON streams values from dataChan as newline-delimited JSON (application/x-ndjson), flushing after each value. It returns nil when the channel is closed and the request context's error when the client goes away, even while idle. Producers must stop on the same context: a producer blocked sending to an abandoned channel would leak.

func (*Context) String

func (c *Context) String(code int, msg string) error

String sends a plain text response

type Engine

type Engine struct {
	// ErrorHandler renders an error returned by a handler before any response
	// bytes were written. The default maps *HTTPError to its status and
	// message and answers 500 "Internal Server Error" for everything else,
	// without leaking the error text. Set it before serving.
	ErrorHandler func(*Context, error)
	// contains filtered or unexported fields
}

Engine is the core framework instance. Routing is delegated to the standard library http.ServeMux, so route patterns use its syntax:

/users/{id}        single-segment parameter
/files/{path...}   remaining path (may be empty)
/{$}               exactly "/"

Static segments take precedence over parameters, and registering two patterns that overlap ambiguously (or the same pattern and method twice) panics at registration time.

func New

func New() *Engine

New creates a new Engine instance

func (*Engine) DELETE

func (e *Engine) DELETE(path string, h HandlerFunc)

func (*Engine) GET

func (e *Engine) GET(path string, h HandlerFunc)

HTTP method shortcuts

func (*Engine) Group

func (e *Engine) Group(prefix string) *Group

Group creates a new route group with a shared prefix. The prefix must be empty or start with "/" and must not end with "/".

func (*Engine) HEAD

func (e *Engine) HEAD(path string, h HandlerFunc)

func (*Engine) Handle

func (e *Engine) Handle(method, pattern string, handler HandlerFunc)

Handle registers a route with any HTTP method. A GET route also answers HEAD, as with net/http.

func (*Engine) Listen

func (e *Engine) Listen(addr string) error

Listen starts the HTTP server with the default timeouts of Server.

func (*Engine) OPTIONS

func (e *Engine) OPTIONS(path string, h HandlerFunc)

func (*Engine) PATCH

func (e *Engine) PATCH(path string, h HandlerFunc)

func (*Engine) POST

func (e *Engine) POST(path string, h HandlerFunc)

func (*Engine) PUT

func (e *Engine) PUT(path string, h HandlerFunc)

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler

func (*Engine) Server

func (e *Engine) Server(addr string) *http.Server

Server returns an http.Server serving this engine with safe default timeouts. Adjust the fields (TLSConfig, timeouts, BaseContext...) before calling ListenAndServe or Serve.

func (*Engine) Use

func (e *Engine) Use(middleware ...MiddlewareFunc)

Use adds global per-route middleware. It applies to routes registered after the call; the first Use call is the outermost middleware.

func (*Engine) Wrap

func (e *Engine) Wrap(middleware ...HTTPMiddleware)

Wrap adds HTTP middleware around the entire engine (outside routing). The first Wrap call is the outermost layer. It panics if the engine already served a request.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group represents a route group with a shared prefix and middleware

func (*Group) DELETE

func (g *Group) DELETE(path string, h HandlerFunc)

func (*Group) GET

func (g *Group) GET(path string, h HandlerFunc)

HTTP method shortcuts for Group

func (*Group) Group

func (g *Group) Group(prefix string) *Group

Group creates a nested group that inherits a copy of this group's middleware at creation time.

func (*Group) HEAD

func (g *Group) HEAD(path string, h HandlerFunc)

func (*Group) Handle

func (g *Group) Handle(method, path string, handler HandlerFunc)

Handle registers a route within the group

func (*Group) OPTIONS

func (g *Group) OPTIONS(path string, h HandlerFunc)

func (*Group) PATCH

func (g *Group) PATCH(path string, h HandlerFunc)

func (*Group) POST

func (g *Group) POST(path string, h HandlerFunc)

func (*Group) PUT

func (g *Group) PUT(path string, h HandlerFunc)

func (*Group) Use

func (g *Group) Use(middleware ...MiddlewareFunc)

Use adds middleware to this group. Group middleware runs inside engine middleware and applies to routes registered after the call.

type HTTPError

type HTTPError struct {
	Status  int
	Message string
	Err     error
}

HTTPError is an error with an HTTP status. The default Engine error handler renders it as a plain-text response with Message (or the status text).

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) Unwrap

func (e *HTTPError) Unwrap() error

type HTTPMiddleware

type HTTPMiddleware func(http.Handler) http.Handler

HTTPMiddleware wraps the whole engine, before routing and method dispatch. Use it (through Engine.Wrap) for concerns that must also see unmatched requests and preflights, such as CORS.

func CORS

func CORS(config ...CORSConfig) HTTPMiddleware

CORS returns HTTP middleware that handles CORS. Register it with Engine.Wrap so preflight requests are answered before routing and method dispatch, whether or not an OPTIONS route exists.

Requests from origins that are not allowed pass through untouched, without CORS headers. Credentials are never allowed.

type HandlerFunc

type HandlerFunc func(*Context) error

HandlerFunc defines the handler signature with error return

type MiddlewareFunc

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc defines the per-route middleware signature. It wraps a HandlerFunc at registration time and runs only for matched routes.

func Logger

func Logger() MiddlewareFunc

Logger returns a middleware that logs request info

func Recovery

func Recovery() MiddlewareFunc

Recovery returns a middleware that recovers from panics. The panic becomes an error returned to the engine, so it is rendered by the normal error handler, or only logged when the response was already started.

type SSEWriter

type SSEWriter struct {
	// contains filtered or unexported fields
}

SSEWriter writes Server-Sent Events from the handler goroutine. There is no producer goroutine or channel: the caller emits events as work completes.

func (*SSEWriter) Event

func (s *SSEWriter) Event(name string, data any) error

Event writes one event ("event:" and "data:" lines plus the blank-line terminator) with data encoded as compact JSON, then flushes. It returns an error once the request context is done or a write fails; callers must stop producing at that point.

Directories

Path Synopsis
Command main is a local tool-execution server built on Blaze.
Command main is a local tool-execution server built on Blaze.
agent-loop command
Command agent-loop runs a complete model round trip with Blaze's built-in tools, against OpenAI and against Anthropic.
Command agent-loop runs a complete model round trip with Blaze's built-in tools, against OpenAI and against Anthropic.
mcp module

Jump to

Keyboard shortcuts

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