{"modulePath":"github.com/bitechdev/ResolveSpec","version":"v1.3.14","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package aiproxy\n\nPackage aiproxy is an authenticated reverse proxy for OpenAI-compatible APIs and MCP servers (streamable HTTP). Upstream URLs and keys stay on the server; clients authenticate with the normal security layer and call the proxy instead.\n\n\tp := aiproxy.New(aiproxy.Config{Prefix: \"/ai\"})\n\tp.RegisterOpenAI(aiproxy.OpenAIUpstream{Upstream: aiproxy.Upstream{Name: \"gpt\", BaseURL: \"https://api.openai.com/v1\", APIKey: key}})\n\tp.RegisterMCP(aiproxy.MCPUpstream{Upstream: aiproxy.Upstream{Name: \"tools\", BaseURL: \"http://localhost:3000/mcp\", APIKey: key}})\n\tmux.Handle(\"/ai/\", p.Handler(security.NewAuthMiddleware(securityList)))\n\nClient routes: {prefix}/{name}/v1/... (OpenAI) and {prefix}/{name} (MCP).\n\n## Constants\n\n```go\nconst DefaultProc = \"resolvespec_ai_proxies\"\n```\nDefaultProc is the stored procedure (function) ProcStore calls when no name is given.\n\n## Types\n\n```go\ntype AuditRecord struct {\n\tTime     time.Time\n\tUserID   int\n\tUser     string\n\tRemoteID string\n\tUpstream string\n\tKind     Kind\n\tMethod   string\n\tPath     string // client path, no query string\n\tModel    string\n\tTools    []string\n\tStatus   int\n\tOutcome  Outcome\n\tReason   string // why a request was refused\n\tDuration time.Duration\n\tUsage    Usage\n\tError    string\n}\n```\nAuditRecord is written once per handled request. It holds no bodies and no keys.\n\n```go\ntype AuditSink interface {\n\tRecord(AuditRecord)\n}\n```\nAuditSink receives audit records. It runs on the request path, so keep it fast (queue slow work such as database writes).\n\n```go\ntype Config struct {\n\t// Prefix the handler is mounted under, e.g. \"/ai\". Empty when mounted with http.StripPrefix.\n\tPrefix string\n\t// MaxBodyBytes caps JSON request bodies that are inspected. Default 10 MB.\n\tMaxBodyBytes int64\n\t// StripHeaders are removed from client requests in addition to the defaults\n\t// (Authorization, Cookie, Proxy-Authorization, X-Api-Key).\n\tStripHeaders []string\n\t// Audit receives one record per request. Default: LogAuditSink. Use NopAuditSink to disable.\n\tAudit AuditSink\n}\n```\nConfig configures a Proxy.\n\n```go\ntype Definition struct {\n\tKind     Kind\n\tUpstream Upstream\n\t// Allowed holds AllowedModels (OpenAI) or AllowedTools (MCP).\n\tAllowed []string\n}\n```\nDefinition describes one upstream independent of how it was registered.\n\n```go\ntype HookContext struct {\n\tContext     context.Context\n\tRequest     *http.Request // BeforeProxy may modify headers/query; the key is injected later\n\tUserContext *security.UserContext\n\n\tUpstream string\n\tKind     Kind\n\tModel    string   // OpenAI: requested model\n\tTools    []string // MCP: tools named by tools/call\n\n\t// AfterProxy only\n\tStatusCode int\n\tDuration   time.Duration\n\tUsage      Usage // OpenAI only; needs stream_options.include_usage for streams\n\tError      error\n\n\t// BeforeProxy only\n\tAbort        bool\n\tAbortMessage string\n\tAbortCode    int // default 403\n}\n```\nHookContext is passed to hooks.\n\n```go\ntype HookFunc func(*HookContext) error\n```\nHookFunc is a hook. A returned error aborts a BeforeProxy request.\n\n```go\ntype HookRegistry struct {\n\t// contains filtered or unexported fields\n}\n```\nHookRegistry holds hooks per type.\n\n```go\nfunc NewHookRegistry() *HookRegistry\n```\nNewHookRegistry creates an empty registry.\n\n```go\nfunc (r *HookRegistry) Execute(t HookType, ctx *HookContext) error\n```\nExecute runs the hooks in order and stops at the first error or abort.\n\n```go\nfunc (r *HookRegistry) Register(t HookType, h HookFunc)\n```\nRegister adds a hook.\n\n```go\ntype HookType string\n```\nHookType defines when a hook runs.\n\n```go\nconst (\n\t// BeforeProxy runs after auth, rate limit and request inspection, before the upstream call.\n\tBeforeProxy HookType = \"before_proxy\"\n\t// AfterProxy runs once the response finished (or failed). Errors are logged only.\n\tAfterProxy HookType = \"after_proxy\"\n)\n```\n\n```go\ntype Kind string\n```\nKind is the type of an upstream.\n\n```go\nconst (\n\tKindOpenAI Kind = \"openai\"\n\tKindMCP    Kind = \"mcp\"\n)\n```\n\n```go\ntype LogAuditSink struct{}\n```\nLogAuditSink writes records through pkg/logger. It is the default sink.\n\n```go\nfunc (LogAuditSink) Record(r AuditRecord)\n```\nRecord implements AuditSink.\n\n```go\ntype MCPUpstream struct {\n\tUpstream\n\t// AllowedTools restricts tools/call to these tool names. Empty means any.\n\tAllowedTools []string\n}\n```\nMCPUpstream is an MCP server speaking streamable HTTP.\n\n```go\ntype NopAuditSink struct{}\n```\nNopAuditSink discards records (use it to switch the default logging off).\n\n```go\nfunc (NopAuditSink) Record(AuditRecord)\n```\nRecord implements AuditSink.\n\n```go\ntype OpenAIUpstream struct {\n\tUpstream\n\t// AllowedModels restricts the \"model\" a request may use. Empty means any.\n\t// When set, write requests must be JSON bodies carrying an allowed model.\n\tAllowedModels []string\n}\n```\nOpenAIUpstream is an OpenAI-compatible API (OpenAI, Azure, Ollama, vLLM, ...).\n\n```go\ntype Outcome string\n```\nOutcome classifies a handled request.\n\n```go\nconst (\n\tOutcomeOK            Outcome = \"ok\"             // upstream answered \u003c 400\n\tOutcomeUpstreamError Outcome = \"upstream_error\" // upstream answered \u003e= 400 or failed\n\tOutcomeDenied        Outcome = \"denied\"         // refused by auth, roles, allowlist, size or a hook\n\tOutcomeRateLimited   Outcome = \"rate_limited\"\n)\n```\n\n```go\ntype ProcStore struct {\n\t// contains filtered or unexported fields\n}\n```\nProcStore loads upstream definitions from a stored procedure (PostgreSQL), using the same contract as the security procedures:\n\n\tSELECT p_success, p_error, p_data FROM resolvespec_ai_proxies()\n\np\\_data is a JSON array; each element has: name, kind (\"openai\"|\"mcp\"), base\\_url, and optionally api\\_key, auth\\_header, auth\\_format, headers (object), allowed\\_roles (array), allowed (array: models or tools), rate\\_per\\_second, rate\\_burst, timeout\\_seconds, enabled (default true). See resolvespec\\_ai\\_proxies.sql.\n\n```go\nfunc NewProcStore(db *sql.DB, proc string) (*ProcStore, error)\n```\nNewProcStore calls proc through db. An empty proc means DefaultProc.\n\n```go\nfunc NewProcStoreFromDatabase(db common.Database, proc string) (*ProcStore, error)\n```\nNewProcStoreFromDatabase is NewProcStore for an application's common.Database. The connection is fetched on every call, so adapter reconnects are followed.\n\n```go\nfunc (s *ProcStore) List(ctx context.Context) ([]Definition, error)\n```\nList implements UpstreamStore. Disabled and undecodable entries are skipped.\n\n```go\ntype Proxy struct {\n\t// contains filtered or unexported fields\n}\n```\nProxy routes authenticated requests to registered upstreams.\n\n```go\nfunc New(cfg Config) *Proxy\n```\nNew creates a Proxy.\n\n```go\nfunc (p *Proxy) AutoReload(ctx context.Context, store UpstreamStore, interval time.Duration) error\n```\nAutoReload calls Reload now and then every interval until ctx ends. The first error is returned; later ones are logged.\n\n```go\nfunc (p *Proxy) Handler(auth func(http.Handler) http.Handler) http.Handler\n```\nHandler returns the proxy handler. auth is the authentication middleware, normally security.NewAuthMiddleware(securityList). It is required: without it every request is refused.\n\n```go\nfunc (p *Proxy) Hooks() *HookRegistry\n```\nHooks returns the hook registry.\n\n```go\nfunc (p *Proxy) Names() []string\n```\nNames lists registered upstream names (no URLs or keys).\n\n```go\nfunc (p *Proxy) Register(d Definition) error\n```\nRegister registers an upstream from a Definition. The name must be unused.\n\n```go\nfunc (p *Proxy) RegisterMCP(u MCPUpstream) error\n```\nRegisterMCP registers an MCP server (streamable HTTP).\n\n```go\nfunc (p *Proxy) RegisterOpenAI(u OpenAIUpstream) error\n```\nRegisterOpenAI registers an OpenAI-compatible upstream.\n\n```go\nfunc (p *Proxy) Reload(ctx context.Context, store UpstreamStore) error\n```\nReload syncs the store-managed upstreams with the store.\n\n  - New definitions are added, changed ones replaced, unchanged ones left alone (their rate-limit state and connections survive), missing ones removed.\n  - Upstreams registered in code are never replaced or removed; a stored definition with the same name is skipped and reported.\n  - Invalid definitions are skipped and reported in the returned error; valid ones are still applied. If the store itself fails, nothing changes.\n\n```go\nfunc (p *Proxy) Unregister(name string) bool\n```\nUnregister removes an upstream (code-registered or loaded). It reports whether it existed. In-flight requests finish normally.\n\n```go\ntype RateLimit struct {\n\tPerSecond float64 // sustained requests per second\n\tBurst     int     // bucket size; defaults to ceil(PerSecond), min 1\n}\n```\nRateLimit limits requests per user per upstream (token bucket).\n\n```go\ntype Upstream struct {\n\t// Name is the route segment clients use: {prefix}/{Name}/...\n\tName string\n\t// BaseURL of the upstream. OpenAI: include the version path (https://api.openai.com/v1).\n\t// MCP: the full streamable HTTP endpoint (http://localhost:3000/mcp).\n\tBaseURL string\n\t// APIKey is sent to the upstream. Never exposed to clients or logs.\n\tAPIKey string\n\t// AuthHeader carries the key. Default \"Authorization\". Applies to OpenAI and MCP upstreams.\n\tAuthHeader string\n\t// AuthFormat renders the header value; %s is the key (e.g. \"Bearer %s\", \"Token %s\", \"%s\").\n\t// Default: \"Bearer %s\" for the Authorization header, \"%s\" (raw key) for any other header.\n\tAuthFormat string\n\t// Headers are extra static headers sent to the upstream (applied before the key header).\n\t// Per-request values can be set in a BeforeProxy hook.\n\tHeaders map[string]string\n\t// AllowedRoles: caller needs at least one. Empty means any authenticated user.\n\tAllowedRoles []string\n\t// RateLimit per user for this upstream. Nil means unlimited.\n\tRateLimit *RateLimit\n\t// Timeout waiting for the upstream response headers. Default 120s. Streams are not cut off.\n\tTimeout time.Duration\n}\n```\nUpstream holds the settings shared by every upstream kind.\n\n```go\nfunc (u Upstream) GoString() string\n```\nGoString redacts the key (%#v).\n\n```go\nfunc (u Upstream) MarshalJSON() ([]byte, error)\n```\nMarshalJSON redacts the key.\n\n```go\nfunc (u Upstream) String() string\n```\nString redacts the key.\n\n```go\ntype UpstreamStore interface {\n\tList(ctx context.Context) ([]Definition, error)\n}\n```\nUpstreamStore supplies upstream definitions for Reload.\n\n```go\ntype Usage struct {\n\tPromptTokens     int64\n\tCompletionTokens int64\n\tTotalTokens      int64\n}\n```\nUsage is the token usage reported by an OpenAI upstream.\n\n","path":"github.com/bitechdev/ResolveSpec/pkg/aiproxy","name":"aiproxy","synopsis":"Package aiproxy is an authenticated reverse proxy for OpenAI-compatible APIs and MCP servers (streamable HTTP).","isRedistributable":true}
