From 7d1d6b77c976be671cac3c33e8d2876eba394b36 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 00:05:38 +0100 Subject: [PATCH 01/13] [AI-3673] HTTP connectors: manifest model for http tools (#2303) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Targets the feature branch `feature/ai-3669-http-connectors` (epic AI-3669), not `main`. Leaf 1 of 4 in the router: [AI-3673](https://linear.app/stream/issue/AI-3673). ## Why Core cannot describe an http connector: `SourceKindMCP` is the only source kind, `SourceRule` has no tool list, and `AsCustom` refuses every manifest that is not MCP-shaped (`core/custom.go:75` on the base). Leaves 2-4 (the `sources/http` ToolSource, call-time safety, the API) need a manifest model to build on. This PR adds only the model and its rules. No source runs http tools yet, and no API or CLI changes. ## How it works The new manifest shape (JSON as stored, `http_tools` omitempty, so no migration): ``` Manifest ├─ endpoints │ └─ http: https://api.weather.example/v1 <- custom base_url (role "http") └─ sources[] └─ kind: http, endpoint: http └─ http_tools[] <- new, only on kind http ├─ name ^[A-Za-z0-9_-]{1,63}$, unique ├─ description <= 1000 bytes ├─ method GET HEAD POST PUT PATCH DELETE ├─ path /..., not // or \, no ? # . .. or stray brace, <= 2048 │ every {p} is a declared, required parameter ├─ parameters <= 64, {name: {type, description, required}} │ name: RFC 3986 unreserved, <= 64 bytes │ type: string | number | integer | boolean └─ read_only only with GET or HEAD ``` What Validate now refuses on an http source, and what it leaves alone: ``` source.kind == "http"? ├─ yes -> checkHTTPSource (http_tools.go) │ ├─ read_only_tools set -> refused (say read_only per tool) │ ├─ outbound: false -> refused (same) │ ├─ header or parameter named -> refused │ │ x-http-method-override, x-http-method, │ │ x-method-override, _method (any case) │ └─ the tool rules in the tree above └─ no -> http_tools set? -> refused; else exactly as on the base ``` `read_only: true` joins `read_only_tools` where they are read: `SourceRule.SendsOutTool` (manifest.go), which `listConnectionTools` and the sensitive-connector check already call. `connectionReads` clears it, as it clears `read_only_tools`, since both are read from the latest revision. | Change | Result | Test | | --- | --- | --- | | `CustomConnector.BaseURL` + `Tools` | `CustomManifest` builds one http source; MCP endpoint and base_url together, or base_url with no tool, are refused | `CustomSuite/TestAnHTTPConnector*` | | `AsCustom` reads the http source back | the data move (`store/datamove.go:1656`) imports an http custom definition, and refuses one that breaks a rule | `DataMoveSuite/TestAnImportedHTTPDefinition*` | | Schemes as for custom MCP | `oauth2_client_credentials` and an operator client still refused; `oauth2_code` refused for http in v1 (discovery needs an issuer or endpoints a custom connector cannot set) | `CustomSuite/TestAnHTTPConnectorTakesTheSchemesAnMCPOneTakes` | | Every rule above | one table row per rule and input shape, accept and refuse | `HTTPSourceSuite/TestAValidHTTPSourceIsAccepted`, `.../TestAnHTTPSourceBreakingARuleIsRefused` | Each cap names its source in `http_tools.go`: 128 tools = the binding's `tools` cap (configs.go); 63-char names so `__` fits Anthropic's 128 (`^[a-zA-Z0-9_-]{1,128}$`, platform.claude.com define-tools; OpenAI's 64 does not hold a longest alias and name, as for MCP today); 64-byte parameter names = OpenAI's function-name cap; 1000 and 2048 = the custom connector's description and endpoint caps (connectors.go); 64 parameters = the config's binding cap. The override names are the three headers the sandbox egress proxy refuses (`methodOverrides`, sandbox/egress/proxy.go:576) plus `_method`. ## No change for MCP - A probe run on the base (8af123d92) and on head over every built-in provider manifest, every stress-test fixture, and a table of `CustomManifest`/`AsCustom` inputs: same Validate answer, same JSON hash, same custom JSON. Two differences only: the `AsCustom` refusal sentence now names "an MCP endpoint or an http base_url and tools", and an http-shaped manifest is no longer refused. - The stress-test fixtures (`testdata/manifests/*.yaml`) already have `kind: http` sources with no tools; an http source may stay empty, so they still parse. - `CustomSuite/TestAnMCPConnectorIsStoredAsBeforeHTTPConnectors` and `.../TestAnMCPConnectorIsRefusedAsBeforeHTTPConnectors` hold the base's JSON and refusals as literals; both were run on the base sha and pass there. ## Validation - `go test ./internal/connectors/... ./internal/store/...` pass; `go test -tags integration -run TestDataMoveSuite ./internal/store/` pass on a database of its own; both new data-move tests fail on the base. - `go vet ./...` and `go vet -tags integration ./...` clean. - Mutation: 70 mutants over every added condition, constant and list entry, 70 killed, and round 1 adds five more (`//`, backslash, rune-vs-byte description, no-tool source, oauth2_code), each killed; one more (the early returns in `checkHTTPPath`) survived and the returns were removed. ## Open questions - The custom http endpoint role is `http`, not `api_base`, so a custom http connector takes no direct call through `/v1/agents/connections/{id}/proxy/` (proxyBase, connection_proxy.go:35), as a custom MCP one takes none. Switching to `api_base` would open the proxy for them. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 --- .../internal/connectors/core/AGENTS.md | 2 + .../internal/connectors/core/custom.go | 57 ++++- .../internal/connectors/core/custom_test.go | 202 ++++++++++++++++ .../internal/connectors/core/http_tools.go | 179 ++++++++++++++ .../connectors/core/http_tools_test.go | 223 ++++++++++++++++++ .../internal/connectors/core/manifest.go | 24 +- acceleration/internal/store/datamove_test.go | 26 ++ 7 files changed, 696 insertions(+), 17 deletions(-) create mode 100644 acceleration/internal/connectors/core/custom_test.go create mode 100644 acceleration/internal/connectors/core/http_tools.go create mode 100644 acceleration/internal/connectors/core/http_tools_test.go diff --git a/acceleration/internal/connectors/core/AGENTS.md b/acceleration/internal/connectors/core/AGENTS.md index e144aa4538..41a80c1567 100644 --- a/acceleration/internal/connectors/core/AGENTS.md +++ b/acceleration/internal/connectors/core/AGENTS.md @@ -55,6 +55,8 @@ A manifest has `sources`, a `channel` block, or both: Linear has only `sources`, `sensitive: true` marks a connector that reads private data, and `sources[].outbound: false` says a source offers only tools that read, and `sources[].read_only_tools` names the ones that read on a source that also offers tools that write; left out, a tool may write and counts as sending data out. A config binding a sensitive connector is refused beside any binding granting a tool that may send out (`providers/AGENTS.md`, `sensitiveBindingsComplaint`). +A source of kind `http` (`SourceKindHTTP`, `http_tools.go`) lists its own tools in `sources[].http_tools`: each a name, a description, a method, a path under the source's endpoint with `{name}` placeholders, scalar `parameters` and `read_only`. `read_only` is allowed only on GET and HEAD, and it is where an http source says a tool only reads: `read_only_tools` and `outbound: false` are refused on one. A parameter or source header named as a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method`, in any case) is refused, so a read-only GET cannot be run as a write. A custom connector is an MCP endpoint or an http `base_url` with tools (`CustomManifest`), under the endpoint role `http`. No source runs http tools yet. + | Term | What it is | In code | | --- | --- | --- | | channel block | How a provider's inbound request is verified, where it keeps each message and each signal, and how a reply goes back | `ChannelRule`, manifest `channel` | diff --git a/acceleration/internal/connectors/core/custom.go b/acceleration/internal/connectors/core/custom.go index d30b279b05..c654c0b3ce 100644 --- a/acceleration/internal/connectors/core/custom.go +++ b/acceleration/internal/connectors/core/custom.go @@ -9,8 +9,9 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) -// CustomConnector is what a custom MCP connector is made of: the fields an app sends to create -// one. The rest of its manifest is fixed (CustomManifest). +// CustomConnector is what a custom connector is made of: the fields an app sends to create one, +// with an MCP endpoint or an http base URL and tools. The rest of its manifest is fixed +// (CustomManifest). type CustomConnector struct { ID string Name string @@ -18,19 +19,25 @@ type CustomConnector struct { Description string // Endpoint is the MCP server. Endpoint string - Schemes []string - Scopes []string - Client ClientPolicy + // BaseURL is the API an http connector's tools call, each at its path under it, and Tools + // are those tools. Set, Endpoint is not. + BaseURL string + Tools []HTTPTool + Schemes []string + Scopes []string + Client ClientPolicy } // CustomManifest is the manifest a custom connector is stored as, or why it cannot be: one MCP -// source at Endpoint, and of the client only its registration, auth_method and alg. Which -// schemes the deployment has and whether Endpoint is public are the caller's to check. +// source at Endpoint, or one http source at BaseURL with Tools, and of the client only its +// registration, auth_method and alg. Which schemes the deployment has and whether Endpoint or +// BaseURL is public are the caller's to check. // // SourceKindMCP is both the tool source and the endpoint role it runs against, as the built-in // manifests write them (internal/connectors/providers/linear.yaml: sources: [{kind: mcp, -// endpoint: mcp}]). MCP is the only source so far (architecture doc, «Layers and interfaces», -// the Source registry's first member). +// endpoint: mcp}]), and SourceKindHTTP is both for an http connector. Its role is not +// api_base, which a connection's direct call goes to (proxyBase, internal/api/connection_proxy.go), +// so an http connector takes no direct call, as an MCP one takes none. func CustomManifest(c CustomConnector) (Manifest, error) { // An operator client is the deployment's own, read from the variables a built-in's // client.env names, and the deployment has none registered with an app's own server. @@ -44,8 +51,8 @@ func CustomManifest(c CustomConnector) (Manifest, error) { return Manifest{}, stack.Wrap(errors.New("client.registration is required with oauth2_code: name how the OAuth client is registered (customer, cimd or dcr)")) } // oauth2_client_credentials gets its token URL from endpoints.token (tokenEndpoint in - // internal/connectors/schemes/oauth2cc/scheme.go), and a custom connector sets only the MCP endpoint, so - // such a definition could be stored and never connected. + // internal/connectors/schemes/oauth2cc/scheme.go), and a custom connector sets only the MCP endpoint or + // the http base URL, so such a definition could be stored and never connected. if slices.Contains(c.Schemes, "oauth2_client_credentials") { return Manifest{}, stack.Wrap(errors.New("oauth2_client_credentials is not available for a custom connector: it needs a token endpoint a custom connector cannot set")) } @@ -62,6 +69,24 @@ func CustomManifest(c CustomConnector) (Manifest, error) { Scopes: ScopePolicy{List: c.Scopes}, Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP}}, } + if c.BaseURL != "" || len(c.Tools) > 0 { + if c.Endpoint != "" { + return Manifest{}, stack.Wrap(errors.New("a custom connector has an MCP endpoint or an http base_url and tools, not both")) + } + // An http source offers only the tools it lists, so one with none could be stored and + // never offer a tool. + if len(c.Tools) == 0 { + return Manifest{}, stack.Wrap(errors.New("an http custom connector needs at least one tool")) + } + // oauth2_code finds the authorization server from the manifest's issuer, authorize and token + // endpoints, which a custom connector cannot set, or from its MCP endpoint, which an http + // one has none of (discover in internal/connectors/schemes/oauth2code/discovery.go). + if slices.Contains(c.Schemes, "oauth2_code") { + return Manifest{}, stack.Wrap(errors.New("oauth2_code is not available for an http custom connector: it needs authorization server endpoints an http connector cannot set")) + } + manifest.Endpoints = map[string]string{SourceKindHTTP: c.BaseURL} + manifest.Sources = []SourceRule{{Kind: SourceKindHTTP, Endpoint: SourceKindHTTP, HTTPTools: c.Tools}} + } if err := manifest.Validate(); err != nil { return Manifest{}, err } @@ -73,9 +98,14 @@ func CustomManifest(c CustomConnector) (Manifest, error) { // connector cannot set (an operator client, client.env, its own token endpoint, a hook) is // refused. For a manifest that did not come through CustomManifest, such as an imported one. func (m Manifest) AsCustom(id string) (Manifest, error) { + var tools []HTTPTool + if source := HTTPSource(m.Sources); source != nil { + tools = source.HTTPTools + } rebuilt, err := CustomManifest(CustomConnector{ ID: id, Name: m.Name, Category: m.Category, Description: m.Description, - Endpoint: m.Endpoints[SourceKindMCP], Schemes: m.Schemes, Scopes: m.Scopes.List, Client: m.Client, + Endpoint: m.Endpoints[SourceKindMCP], BaseURL: m.Endpoints[SourceKindHTTP], Tools: tools, + Schemes: m.Schemes, Scopes: m.Scopes.List, Client: m.Client, }) if err != nil { return Manifest{}, err @@ -93,7 +123,8 @@ func (m Manifest) AsCustom(id string) (Manifest, error) { } if string(want) != string(got) { return Manifest{}, stack.Wrap(errors.New("it is not a manifest a custom connector can have: a custom connector has an id, a name, " + - "a category, a description, an MCP endpoint, schemes, scopes and a client's registration, auth_method and alg, and nothing else")) + "a category, a description, an MCP endpoint or an http base_url and tools, schemes, scopes and a client's registration, " + + "auth_method and alg, and nothing else")) } return rebuilt, nil } diff --git a/acceleration/internal/connectors/core/custom_test.go b/acceleration/internal/connectors/core/custom_test.go new file mode 100644 index 0000000000..dceaeb9bed --- /dev/null +++ b/acceleration/internal/connectors/core/custom_test.go @@ -0,0 +1,202 @@ +package core + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/suite" +) + +// CustomSuite runs CustomManifest and AsCustom, the two ways a custom connector's manifest is made. +type CustomSuite struct { + suite.Suite +} + +func TestCustomSuite(t *testing.T) { + suite.Run(t, new(CustomSuite)) +} + +// mcpCustom is a custom MCP connector with every field a custom one may set, the client's env +// among what it may not. +func mcpCustom() CustomConnector { + return CustomConnector{ID: "custom_acme", Name: " Acme ", Category: " crm ", Description: " Acme CRM ", + Endpoint: "https://mcp.acme.example/mcp", Schemes: []string{"oauth2_code", "bearer"}, Scopes: []string{"read", "write"}, + Client: ClientPolicy{Registration: []ClientRegistrationMethod{ClientCustomer}, AuthMethod: AuthClientSecretPost, Env: "IGNORED"}} +} + +// httpCustom is a custom http connector with a tool that reads and one that writes. +func httpCustom() CustomConnector { + writes := forecast() + writes.Name, writes.Method, writes.Path, writes.ReadOnly = "create_alert", "POST", "/alerts", false + writes.Parameters = map[string]HTTPParameter{"city": {Type: "string", Required: true}} + return CustomConnector{ID: "custom_weather", Name: "Weather", BaseURL: "https://api.weather.example/v1", + Tools: []HTTPTool{forecast(), writes}, Schemes: []string{"api_key"}} +} + +func (s *CustomSuite) json(m Manifest) string { + raw, err := json.Marshal(m) + s.Require().NoError(err) + return string(raw) +} + +// The JSON an MCP connector is stored as, and what AsCustom gives back for it, are what the base +// (8af123d92) gave: each expected string below is the output of a probe run there. +func (s *CustomSuite) TestAnMCPConnectorIsStoredAsBeforeHTTPConnectors() { + for name, test := range map[string]struct { + custom CustomConnector + stored string + }{ + "every field": {mcpCustom(), `{"id":"custom_acme","revision":1,"name":"Acme","category":"crm","description":"Acme CRM",` + + `"endpoints":{"mcp":"https://mcp.acme.example/mcp"},"schemes":["oauth2_code","bearer"],` + + `"client":{"registration":["customer"],"auth_method":"client_secret_post"},"scopes":{"list":["read","write"]},` + + `"sources":[{"kind":"mcp","endpoint":"mcp"}]}`}, + "a bearer server": {CustomConnector{ID: "custom_acme", Name: "Acme", Endpoint: "https://mcp.acme.example/mcp", Schemes: []string{"bearer"}}, + `{"id":"custom_acme","revision":1,"name":"Acme","endpoints":{"mcp":"https://mcp.acme.example/mcp"},"schemes":["bearer"],` + + `"sources":[{"kind":"mcp","endpoint":"mcp"}]}`}, + } { + m, err := CustomManifest(test.custom) + s.Require().NoError(err, name) + s.Equal(test.stored, s.json(m), name) + + m.Revision = 3 + back, err := m.AsCustom("custom_acme") + s.Require().NoError(err, name) + s.Equal(m, back, name) + } +} + +// The refusals of an MCP connector are the base's (8af123d92), each from the same probe. +func (s *CustomSuite) TestAnMCPConnectorIsRefusedAsBeforeHTTPConnectors() { + for name, test := range map[string]struct { + change func(c *CustomConnector) + refusal string + }{ + "client credentials": {func(c *CustomConnector) { c.Schemes = []string{"oauth2_client_credentials"} }, + "oauth2_client_credentials is not available for a custom connector: it needs a token endpoint a custom connector cannot set"}, + "an operator client": {func(c *CustomConnector) { c.Client.Registration = []ClientRegistrationMethod{ClientOperator} }, + "client.registration cannot be operator for a custom connector: this deployment has no client registered with it"}, + "oauth2_code without a registration": {func(c *CustomConnector) { c.Client = ClientPolicy{} }, + "client.registration is required with oauth2_code: name how the OAuth client is registered (customer, cimd or dcr)"}, + "a plain http server": {func(c *CustomConnector) { c.Endpoint = "http://mcp.acme.example/mcp" }, + `manifest "custom_acme": endpoints.mcp: "http://mcp.acme.example/mcp" does not start with https:// or a placeholder`}, + "no endpoint": {func(c *CustomConnector) { c.Endpoint = "" }, + `manifest "custom_acme": endpoints.mcp: "" does not start with https:// or a placeholder`}, + } { + custom := mcpCustom() + test.change(&custom) + _, err := CustomManifest(custom) + s.EqualError(err, test.refusal, name) + } +} + +func (s *CustomSuite) TestAnHTTPConnectorIsStoredAsOneHTTPSourceAtItsBaseURL() { + m, err := CustomManifest(httpCustom()) + + s.Require().NoError(err) + s.JSONEq(`{"id":"custom_weather","revision":1,"name":"Weather","endpoints":{"http":"https://api.weather.example/v1"}, + "schemes":["api_key"],"sources":[{"kind":"http","endpoint":"http","http_tools":[ + {"name":"get_forecast","description":"The forecast for a city.","method":"GET","path":"/forecast/{city}","read_only":true, + "parameters":{"city":{"type":"string","description":"The city.","required":true},"days":{"type":"integer"}}}, + {"name":"create_alert","description":"The forecast for a city.","method":"POST","path":"/alerts", + "parameters":{"city":{"type":"string","required":true}}}]}]}`, s.json(m)) + s.False(m.SendsOutTool("get_forecast")) + s.True(m.SendsOutTool("create_alert")) +} + +func (s *CustomSuite) TestAnHTTPConnectorReadsBackAsItself() { + m, err := CustomManifest(httpCustom()) + s.Require().NoError(err) + m.Revision = 2 + + back, err := m.AsCustom("custom_weather") + + s.Require().NoError(err) + s.Equal(m, back) +} + +// An http connector takes the schemes an MCP one does: oauth2_client_credentials still needs a +// token endpoint it cannot set, and an operator client is still the deployment's own. +func (s *CustomSuite) TestAnHTTPConnectorTakesTheSchemesAnMCPOneTakes() { + for name, test := range map[string]struct { + change func(c *CustomConnector) + refusal string + }{ + "api_key": {func(c *CustomConnector) {}, ""}, + "bearer": {func(c *CustomConnector) { c.Schemes = []string{"bearer"} }, ""}, + "none": {func(c *CustomConnector) { c.Schemes = []string{"none"} }, ""}, + "oauth2_code": {func(c *CustomConnector) { + c.Schemes, c.Client.Registration = []string{"oauth2_code"}, []ClientRegistrationMethod{ClientDCR} + }, "oauth2_code is not available for an http custom connector"}, + "client credentials": {func(c *CustomConnector) { c.Schemes = []string{"oauth2_client_credentials"} }, + "oauth2_client_credentials is not available for a custom connector"}, + "an operator client": {func(c *CustomConnector) { c.Client.Registration = []ClientRegistrationMethod{ClientOperator} }, + "client.registration cannot be operator"}, + "oauth2_code without a registration": {func(c *CustomConnector) { c.Schemes = []string{"oauth2_code"} }, + "client.registration is required with oauth2_code"}, + } { + custom := httpCustom() + test.change(&custom) + _, err := CustomManifest(custom) + if test.refusal == "" { + s.NoError(err, name) + } else { + s.ErrorContains(err, test.refusal, name) + } + } +} + +func (s *CustomSuite) TestAnHTTPConnectorOfAnotherShapeIsRefused() { + for name, test := range map[string]struct { + change func(c *CustomConnector) + refusal string + }{ + "an MCP endpoint too": {func(c *CustomConnector) { c.Endpoint = "https://mcp.weather.example/mcp" }, + "a custom connector has an MCP endpoint or an http base_url and tools, not both"}, + "no tool": {func(c *CustomConnector) { c.Tools = nil }, "an http custom connector needs at least one tool"}, + "no base URL": {func(c *CustomConnector) { c.BaseURL = "" }, `endpoints.http: "" does not start with https://`}, + "a plain http URL": {func(c *CustomConnector) { c.BaseURL = "http://api.weather.example/v1" }, `endpoints.http: "http://api.weather.example/v1" does not start with https://`}, + "a tool that breaks a rule": {func(c *CustomConnector) { c.Tools[1].ReadOnly = true }, + `sources[0].http_tools[1].read_only: a read-only tool must be GET or HEAD, and "create_alert" is POST`}, + } { + custom := httpCustom() + test.change(&custom) + _, err := CustomManifest(custom) + s.ErrorContains(err, test.refusal, name) + } +} + +// AsCustom keeps an http manifest only when CustomManifest would have made it: anything else a +// manifest says is refused, as for an MCP one. +func (s *CustomSuite) TestAnHTTPManifestWithMoreThanACustomConnectorSetsIsRefused() { + for name, change := range map[string]func(m *Manifest){ + "a source header": func(m *Manifest) { m.Sources[0].Headers = map[string]string{"X-Api-Version": "2"} }, + "needs_scopes": func(m *Manifest) { + m.Sources[0].Tools = []ToolRule{{Name: "get_forecast", NeedsScopes: []string{"read"}}} + }, + "an mcp source too": func(m *Manifest) { + m.Sources = append(m.Sources, SourceRule{Kind: SourceKindMCP, Endpoint: SourceKindHTTP}) + }, + "another endpoint": func(m *Manifest) { m.Endpoints["api_base"] = "https://api.weather.example" }, + "a hook": func(m *Manifest) { m.Hooks = map[string]HookName{HookAfterToken: "weather.check"} }, + "sensitive": func(m *Manifest) { m.Sensitive = true }, + } { + m, err := CustomManifest(httpCustom()) + s.Require().NoError(err) + change(&m) + + _, err = m.AsCustom("custom_weather") + + s.ErrorContains(err, "it is not a manifest a custom connector can have", name) + } +} + +// A manifest with both an MCP and an http endpoint is neither connector, whichever source it has. +func (s *CustomSuite) TestAManifestWithBothEndpointsIsRefused() { + m, err := CustomManifest(httpCustom()) + s.Require().NoError(err) + m.Endpoints[SourceKindMCP] = "https://mcp.weather.example/mcp" + + _, err = m.AsCustom("custom_weather") + + s.ErrorContains(err, "not both") +} diff --git a/acceleration/internal/connectors/core/http_tools.go b/acceleration/internal/connectors/core/http_tools.go new file mode 100644 index 0000000000..5440a9f3d5 --- /dev/null +++ b/acceleration/internal/connectors/core/http_tools.go @@ -0,0 +1,179 @@ +package core + +import ( + "fmt" + "maps" + "net/http" + "regexp" + "slices" + "strings" +) + +// SourceKindHTTP is the sources[].kind of the http source: the tools are the ones the manifest +// lists (SourceRule.HTTPTools), each one HTTP request to the source's endpoint. +const SourceKindHTTP = "http" + +// HTTPTool is one tool of an http source: one request, whose method and path the manifest +// fixes and whose parameters are the values a model gives. +type HTTPTool struct { + Name string `yaml:"name" json:"name"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` + Method string `yaml:"method" json:"method"` + // Path is under the source's endpoint and starts with /. Each {name} in it is the value of + // the parameter of that name. + Path string `yaml:"path" json:"path"` + Parameters map[string]HTTPParameter `yaml:"parameters,omitempty" json:"parameters,omitempty"` + // ReadOnly says the tool only reads, so it sends no data out of the conversation + // (SourceRule.SendsOutTool), as a name in an mcp source's read_only_tools does. Only a GET + // or HEAD tool may say it. + ReadOnly bool `yaml:"read_only,omitempty" json:"read_only,omitempty"` +} + +// HTTPParameter is one value a model gives an http tool. +type HTTPParameter struct { + // Type is a JSON Schema scalar type: string, number, integer or boolean. + Type string `yaml:"type" json:"type"` + Description string `yaml:"description,omitempty" json:"description,omitempty"` + // Required parameters must be given. A parameter in the path is always required. + Required bool `yaml:"required,omitempty" json:"required,omitempty"` +} + +// HTTPSource is the first http source of sources, or nil, as MCPSource is for mcp. +func HTTPSource(sources []SourceRule) *SourceRule { + index := slices.IndexFunc(sources, func(rule SourceRule) bool { return rule.Kind == SourceKindHTTP }) + if index < 0 { + return nil + } + return &sources[index] +} + +// The caps of an http source. Each is a choice, with the limit it is taken from: +const ( + // maxHTTPTools is the most tools a binding grants and a session offers from one binding + // (maxItems on AgentConnectorBinding.tools, internal/api/configs.go), which is the most + // OpenAI documents taking in one request. + maxHTTPTools = 128 + // maxHTTPToolDescription is the cap a custom connector's own description has + // (CustomConnectorRequest.Description, internal/api/connectors.go). + maxHTTPToolDescription = 1000 + // maxHTTPPath is the cap a custom connector's MCP endpoint URL has + // (CustomConnectorRequest.Endpoint, internal/api/connectors.go). + maxHTTPPath = 2048 + // maxHTTPParameters is the cap an agent config has on its connector bindings and its + // visible_tools (internal/api/configs.go). + maxHTTPParameters = 64 + // maxHTTPParameterName is the length OpenAI caps a function name at + // (https://developers.openai.com/api/reference/resources/chat, tools[].function.name). + maxHTTPParameterName = 64 +) + +var ( + // httpMethods are the methods an http tool may send: the five a connection's direct call + // forwards (proxyMethods, internal/api/connection_proxy.go) and HEAD. + httpMethods = []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} + // httpReadMethods are the methods of httpMethods that RFC 9110 section 9.2.1 calls safe, + // the only ones a read_only tool may send. + httpReadMethods = []string{http.MethodGet, http.MethodHead} + // httpParameterTypes are JSON Schema's scalar types (JSON Schema Validation 2020-12 + // section 6.1.1), which a value in a path, a query or a JSON body can be. + httpParameterTypes = []string{"string", "number", "integer", "boolean"} + // httpMethodOverrides are names, lowercase, in which a client names the method a host should + // run in place of the request's: the three headers the sandbox's egress proxy refuses + // (methodOverrides, internal/sandbox/egress/proxy.go; Google runs a GET with + // X-HTTP-Method-Override: POST as the POST, AI-2120) and the _method field Rails and Laravel + // read from a form. A parameter or header named so could make a read_only GET write. + httpMethodOverrides = []string{"x-http-method-override", "x-http-method", "x-method-override", "_method"} + // httpToolName is a name of at most 63 characters: the model is offered it as + // __ (internal/session), an alias is at most 63 characters + // (AgentConnectorBinding.name, internal/api/configs.go), and 63+2+63 is the 128 Anthropic + // caps a tool name at (^[a-zA-Z0-9_-]{1,128}$, + // https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools). OpenAI caps + // a function name at 64 (the reference maxHTTPParameterName cites), so a longest alias and + // name do not fit it: the same holds for an MCP tool today. + httpToolName = regexp.MustCompile(`^[A-Za-z0-9_-]{1,63}$`) + // httpPath is visible ASCII (RFC 9110 section 5.5's vchar), so a path holds no space or + // line break, and no ? or #, so it has no query or fragment of its own. + httpPath = regexp.MustCompile(`^/[!"$->@-~]*$`) +) + +// checkHTTPSource refuses an http source whose tools a session could not offer or that could +// write while saying they read. field names the source. +func checkHTTPSource(fail func(field, format string, args ...any), field string, source SourceRule) { + if len(source.ReadOnlyTools) > 0 { + fail(field+".read_only_tools", "is not set on an http source: each of its tools says read_only") + } + if !source.SendsOut() { + fail(field+".outbound", "is not false on an http source: each of its tools says read_only") + } + for _, name := range slices.Sorted(maps.Keys(source.Headers)) { + if slices.Contains(httpMethodOverrides, strings.ToLower(name)) { + fail(field+".headers."+name, "names a method override") + } + } + if len(source.HTTPTools) > maxHTTPTools { + fail(field+".http_tools", "has %d tools, over %d", len(source.HTTPTools), maxHTTPTools) + } + named := map[string]bool{} + for i, tool := range source.HTTPTools { + field := fmt.Sprintf("%s.http_tools[%d]", field, i) + if !httpToolName.MatchString(tool.Name) { + fail(field+".name", "%q is not 1 to 63 letters, digits, _ or -", tool.Name) + } + if named[tool.Name] { + fail(field+".name", "%q is named twice", tool.Name) + } + named[tool.Name] = true + if len(tool.Description) > maxHTTPToolDescription { + fail(field+".description", "is over %d bytes", maxHTTPToolDescription) + } + if !slices.Contains(httpMethods, tool.Method) { + fail(field+".method", "%q is not one of %v", tool.Method, httpMethods) + } + if tool.ReadOnly && !slices.Contains(httpReadMethods, tool.Method) { + fail(field+".read_only", "a read-only tool must be GET or HEAD, and %q is %s", tool.Name, tool.Method) + } + checkHTTPPath(fail, field, tool) + if len(tool.Parameters) > maxHTTPParameters { + fail(field+".parameters", "has %d parameters, over %d", len(tool.Parameters), maxHTTPParameters) + } + for _, name := range slices.Sorted(maps.Keys(tool.Parameters)) { + field := field + ".parameters." + name + switch { + case len(name) > maxHTTPParameterName || !unreserved.MatchString(name): + fail(field, "%q is not 1 to %d letters, digits, ., _, ~ or -", name, maxHTTPParameterName) + case slices.Contains(httpMethodOverrides, strings.ToLower(name)): + fail(field, "names a method override") + } + if !slices.Contains(httpParameterTypes, tool.Parameters[name].Type) { + fail(field+".type", "%q is not one of %v", tool.Parameters[name].Type, httpParameterTypes) + } + } + } +} + +// checkHTTPPath refuses a tool's path that has a query, a fragment, a leading // or a \, a dot segment, a stray brace +// or a {name} that is not a required parameter of the tool. +func checkHTTPPath(fail func(field, format string, args ...any), field string, tool HTTPTool) { + field += ".path" + switch { + case len(tool.Path) > maxHTTPPath: + fail(field, "is over %d bytes", maxHTTPPath) + case !httpPath.MatchString(tool.Path): + fail(field, "%q does not start with / or holds a space, a ? or a #", tool.Path) + case strings.HasPrefix(tool.Path, "//") || strings.Contains(tool.Path, `\`): + fail(field, "%q starts with // or holds a \\, which a URL join can read as another host or path", tool.Path) + case slices.ContainsFunc(strings.Split(tool.Path, "/"), isDotSegment): + fail(field, "%q has a . or .. segment", tool.Path) + case strings.ContainsAny(placeholder.ReplaceAllString(tool.Path, ""), "{}"): + fail(field, "%q has a { or } that opens or closes no {name}", tool.Path) + } + for _, match := range placeholder.FindAllStringSubmatch(tool.Path, -1) { + parameter, declared := tool.Parameters[match[1]] + switch { + case !declared: + fail(field, "{%s} is not a parameter of the tool", match[1]) + case !parameter.Required: + fail(field, "{%s} is a parameter the tool does not require", match[1]) + } + } +} diff --git a/acceleration/internal/connectors/core/http_tools_test.go b/acceleration/internal/connectors/core/http_tools_test.go new file mode 100644 index 0000000000..b27df640fe --- /dev/null +++ b/acceleration/internal/connectors/core/http_tools_test.go @@ -0,0 +1,223 @@ +package core + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/suite" +) + +// HTTPSourceSuite runs the rules of an http source's tools (checkHTTPSource) through Validate. +type HTTPSourceSuite struct { + suite.Suite +} + +func TestHTTPSourceSuite(t *testing.T) { + suite.Run(t, new(HTTPSourceSuite)) +} + +// forecast is a valid http tool, which each case changes in one place. +func forecast() HTTPTool { + return HTTPTool{Name: "get_forecast", Description: "The forecast for a city.", Method: "GET", Path: "/forecast/{city}", + Parameters: map[string]HTTPParameter{ + "city": {Type: "string", Description: "The city.", Required: true}, + "days": {Type: "integer"}, + }, ReadOnly: true} +} + +// httpManifest is a valid manifest whose one source is an http one with tools. +func httpManifest(tools ...HTTPTool) Manifest { + return Manifest{ID: "example", Revision: 1, Name: "Example", Schemes: []string{"bearer"}, + Endpoints: map[string]string{SourceKindHTTP: "https://api.example.com/v1"}, + Sources: []SourceRule{{Kind: SourceKindHTTP, Endpoint: SourceKindHTTP, HTTPTools: tools}}} +} + +// withTool is httpManifest with forecast changed by change. +func withTool(change func(tool *HTTPTool)) Manifest { + tool := forecast() + change(&tool) + return httpManifest(tool) +} + +// withSource is httpManifest with forecast and its source changed by change. +func withSource(change func(source *SourceRule)) Manifest { + m := httpManifest(forecast()) + change(&m.Sources[0]) + return m +} + +// tools are count copies of forecast, each under a name of its own. +func tools(count int) []HTTPTool { + listed := make([]HTTPTool, count) + for i := range listed { + listed[i] = forecast() + listed[i].Name = fmt.Sprintf("tool_%d", i) + } + return listed +} + +// parameters are count string parameters, the first of them city. +func parameters(count int) map[string]HTTPParameter { + listed := map[string]HTTPParameter{"city": {Type: "string", Required: true}} + for i := 1; i < count; i++ { + listed[fmt.Sprintf("p%d", i)] = HTTPParameter{Type: "string"} + } + return listed +} + +func (s *HTTPSourceSuite) TestAValidHTTPSourceIsAccepted() { + for name, m := range map[string]Manifest{ + "the tool as it is": httpManifest(forecast()), + "no tool, as the stress-test ones": httpManifest(), + "HEAD read only": withTool(func(t *HTTPTool) { t.Method = "HEAD" }), + "POST that is not read only": withTool(func(t *HTTPTool) { t.Method, t.ReadOnly = "POST", false }), + "PUT that is not read only": withTool(func(t *HTTPTool) { t.Method, t.ReadOnly = "PUT", false }), + "PATCH that is not read only": withTool(func(t *HTTPTool) { t.Method, t.ReadOnly = "PATCH", false }), + "DELETE that is not read only": withTool(func(t *HTTPTool) { t.Method, t.ReadOnly = "DELETE", false }), + "GET that is not read only": withTool(func(t *HTTPTool) { t.ReadOnly = false }), + "a number": withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{Type: "number"} }), + "a boolean": withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{Type: "boolean"} }), + "a name of 63 with capitals and -": withTool(func(t *HTTPTool) { t.Name = "Get-" + strings.Repeat("x", 59) }), + "a description of 1000 bytes": withTool(func(t *HTTPTool) { t.Description = strings.Repeat("d", 1000) }), + "no description": withTool(func(t *HTTPTool) { t.Description = "" }), + "a path of 2048 bytes": withTool(func(t *HTTPTool) { t.Path = "/{city}/" + strings.Repeat("p", 2040) }), + "the root path": withTool(func(t *HTTPTool) { t.Path, t.Parameters = "/", nil }), + "a {name} inside a segment": withTool(func(t *HTTPTool) { t.Path = "/files/{city}.json" }), + "an escaped and a reserved character": withTool(func(t *HTTPTool) { t.Path = "/a%20b/c:d;e=f@g!$&'()*+,/{city}" }), + "128 tools": httpManifest(tools(128)...), + "64 parameters": withTool(func(t *HTTPTool) { t.Parameters = parameters(64) }), + "a parameter of 64 with . ~ and -": withTool(func(t *HTTPTool) { t.Parameters["a.b~c-"+strings.Repeat("d", 58)] = HTTPParameter{Type: "string"} }), + "a parameter merely holding method": withTool(func(t *HTTPTool) { t.Parameters["http_method_name"] = HTTPParameter{Type: "string"} }), + "a header that is no override": withSource(func(r *SourceRule) { r.Headers = map[string]string{"X-Api-Version": "2"} }), + "outbound true": withSource(func(r *SourceRule) { r.Outbound = new(true) }), + "needs_scopes for one of its tools": withSource(func(r *SourceRule) { r.Tools = []ToolRule{{Name: "get_forecast", NeedsScopes: []string{"read"}}} }), + "an mcp source with an override header": {ID: "example", Revision: 1, Name: "Example", Schemes: []string{"bearer"}, + Endpoints: map[string]string{SourceKindMCP: "https://api.example.com/mcp"}, + Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP, Headers: map[string]string{"X-HTTP-Method-Override": "POST"}}}}, + } { + s.NoError(m.Validate(), name) + } +} + +func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { + noTool := func(change func(r *SourceRule)) Manifest { m := httpManifest(); change(&m.Sources[0]); return m } + for name, test := range map[string]struct { + manifest Manifest + refusal string + }{ + "a lowercase method": {withTool(func(t *HTTPTool) { t.Method = "get" }), `http_tools[0].method: "get" is not one of`}, + "OPTIONS": {withTool(func(t *HTTPTool) { t.Method, t.ReadOnly = "OPTIONS", false }), `http_tools[0].method: "OPTIONS" is not one of`}, + "TRACE": {withTool(func(t *HTTPTool) { t.Method, t.ReadOnly = "TRACE", false }), `http_tools[0].method: "TRACE" is not one of`}, + "no method": {withTool(func(t *HTTPTool) { t.Method, t.ReadOnly = "", false }), `http_tools[0].method: "" is not one of`}, + "POST read only": {withTool(func(t *HTTPTool) { t.Method = "POST" }), `http_tools[0].read_only: a read-only tool must be GET or HEAD, and "get_forecast" is POST`}, + "PUT read only": {withTool(func(t *HTTPTool) { t.Method = "PUT" }), `is PUT`}, + "PATCH read only": {withTool(func(t *HTTPTool) { t.Method = "PATCH" }), `is PATCH`}, + "DELETE read only": {withTool(func(t *HTTPTool) { t.Method = "DELETE" }), `is DELETE`}, + "no path": {withTool(func(t *HTTPTool) { t.Path = "" }), `http_tools[0].path: "" does not start with /`}, + "a relative path": {withTool(func(t *HTTPTool) { t.Path = "forecast/{city}" }), `does not start with /`}, + "a query": {withTool(func(t *HTTPTool) { t.Path = "/forecast/{city}?units=metric" }), `holds a space, a ? or a #`}, + "a fragment": {withTool(func(t *HTTPTool) { t.Path = "/forecast/{city}#today" }), `holds a space, a ? or a #`}, + "a space": {withTool(func(t *HTTPTool) { t.Path = "/fore cast/{city}" }), `holds a space, a ? or a #`}, + "a line break": {withTool(func(t *HTTPTool) { t.Path = "/forecast/{city}\r\nX-HTTP-Method-Override: POST" }), `holds a space, a ? or a #`}, + "a non-ASCII byte": {withTool(func(t *HTTPTool) { t.Path = "/prévision/{city}" }), `holds a space, a ? or a #`}, + "a leading //": {withTool(func(t *HTTPTool) { t.Path = "//other.example/{city}" }), `starts with // or holds a \`}, + "a backslash": {withTool(func(t *HTTPTool) { t.Path = `/forecast\{city}` }), `starts with // or holds a \`}, + "a .. segment": {withTool(func(t *HTTPTool) { t.Path = "/forecast/../admin/{city}" }), `has a . or .. segment`}, + "a . segment": {withTool(func(t *HTTPTool) { t.Path = "/./{city}" }), `has a . or .. segment`}, + "a trailing ..": {withTool(func(t *HTTPTool) { t.Path = "/{city}/.." }), `has a . or .. segment`}, + "an unclosed brace": {withTool(func(t *HTTPTool) { t.Path = "/forecast/{city" }), `has a { or } that opens or closes no {name}`}, + "a stray close brace": {withTool(func(t *HTTPTool) { t.Path = "/forecast}/{city}" }), `has a { or } that opens or closes no {name}`}, + "a nested brace": {withTool(func(t *HTTPTool) { t.Path = "/{{city}}" }), `has a { or } that opens or closes no {name}`}, + "an empty {}": {withTool(func(t *HTTPTool) { t.Path = "/{city}/{}" }), `{} is not a parameter of the tool`}, + "a path over 2048": {withTool(func(t *HTTPTool) { t.Path = "/{city}/" + strings.Repeat("p", 2041) }), `http_tools[0].path: is over 2048 bytes`}, + "an undeclared {name}": {withTool(func(t *HTTPTool) { t.Path = "/forecast/{town}" }), `http_tools[0].path: {town} is not a parameter of the tool`}, + "an optional {name}": {withTool(func(t *HTTPTool) { t.Path = "/forecast/{city}/{days}" }), `http_tools[0].path: {days} is a parameter the tool does not require`}, + "an array": {withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{Type: "array"} }), `parameters.days.type: "array" is not one of`}, + "an object": {withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{Type: "object"} }), `parameters.days.type: "object" is not one of`}, + "null": {withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{Type: "null"} }), `parameters.days.type: "null" is not one of`}, + "no type": {withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{} }), `parameters.days.type: "" is not one of`}, + "a capitalized type": {withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{Type: "String"} }), `parameters.days.type: "String" is not one of`}, + "_method": {withTool(func(t *HTTPTool) { t.Parameters["_method"] = HTTPParameter{Type: "string"} }), `parameters._method: names a method override`}, + "_METHOD": {withTool(func(t *HTTPTool) { t.Parameters["_METHOD"] = HTTPParameter{Type: "string"} }), `parameters._METHOD: names a method override`}, + "X-HTTP-Method-Override": {withTool(func(t *HTTPTool) { t.Parameters["X-HTTP-Method-Override"] = HTTPParameter{Type: "string"} }), + `parameters.X-HTTP-Method-Override: names a method override`}, + "x-http-method": {withTool(func(t *HTTPTool) { t.Parameters["x-http-method"] = HTTPParameter{Type: "string"} }), `parameters.x-http-method: names a method override`}, + "X-Method-Override": {withTool(func(t *HTTPTool) { t.Parameters["X-Method-Override"] = HTTPParameter{Type: "string"} }), `parameters.X-Method-Override: names a method override`}, + "$httpMethod": {withTool(func(t *HTTPTool) { t.Parameters["$httpMethod"] = HTTPParameter{Type: "string"} }), `parameters.$httpMethod: "$httpMethod" is not 1 to 64`}, + "a bracket": {withTool(func(t *HTTPTool) { t.Parameters["page[size]"] = HTTPParameter{Type: "string"} }), `"page[size]" is not 1 to 64`}, + "a brace": {withTool(func(t *HTTPTool) { t.Parameters["a}b"] = HTTPParameter{Type: "string"} }), `"a}b" is not 1 to 64`}, + "an empty name": {withTool(func(t *HTTPTool) { t.Parameters[""] = HTTPParameter{Type: "string"} }), `"" is not 1 to 64`}, + "a name of 65": {withTool(func(t *HTTPTool) { t.Parameters[strings.Repeat("p", 65)] = HTTPParameter{Type: "string"} }), `is not 1 to 64`}, + "65 parameters": {withTool(func(t *HTTPTool) { t.Parameters = parameters(65) }), `http_tools[0].parameters: has 65 parameters, over 64`}, + "an override header": {withSource(func(r *SourceRule) { r.Headers = map[string]string{"x-HTTP-method-OVERRIDE": "POST"} }), + `sources[0].headers.x-HTTP-method-OVERRIDE: names a method override`}, + "read_only_tools": {withSource(func(r *SourceRule) { r.ReadOnlyTools = []string{"get_forecast"} }), `sources[0].read_only_tools: is not set on an http source`}, + "outbound false": {withSource(func(r *SourceRule) { r.Outbound = new(false) }), `sources[0].outbound: is not false on an http source`}, + "no tool name": {withTool(func(t *HTTPTool) { t.Name = "" }), `http_tools[0].name: "" is not 1 to 63 letters, digits, _ or -`}, + "a dot": {withTool(func(t *HTTPTool) { t.Name = "forecast.get" }), `"forecast.get" is not 1 to 63`}, + "a space in a name": {withTool(func(t *HTTPTool) { t.Name = "get forecast" }), `"get forecast" is not 1 to 63`}, + "a name of 64": {withTool(func(t *HTTPTool) { t.Name = strings.Repeat("x", 64) }), `is not 1 to 63`}, + "a name twice": {httpManifest(forecast(), forecast()), `http_tools[1].name: "get_forecast" is named twice`}, + "a description of 1001 bytes in 501 characters": {withTool(func(t *HTTPTool) { t.Description = strings.Repeat("é", 500) + "d" }), `http_tools[0].description: is over 1000 bytes`}, + "outbound false on a source with no tool": {noTool(func(r *SourceRule) { r.Outbound = new(false) }), `sources[0].outbound: is not false on an http source`}, + "read_only_tools on a source with no tool": {noTool(func(r *SourceRule) { r.ReadOnlyTools = []string{"x"} }), `sources[0].read_only_tools: is not set on an http source`}, + "an override header on a source with no tool": {noTool(func(r *SourceRule) { r.Headers = map[string]string{"X-HTTP-Method": "PUT"} }), `names a method override`}, + "a description over 1000": {withTool(func(t *HTTPTool) { t.Description = strings.Repeat("d", 1001) }), `http_tools[0].description: is over 1000 bytes`}, + "129 tools": {httpManifest(tools(129)...), `sources[0].http_tools: has 129 tools, over 128`}, + "http_tools on an mcp source": {Manifest{ID: "example", Revision: 1, Name: "Example", Schemes: []string{"bearer"}, + Endpoints: map[string]string{SourceKindMCP: "https://api.example.com/mcp"}, + Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP, HTTPTools: []HTTPTool{forecast()}}}}, + `sources[0].http_tools: is set only on a source of kind http`}, + "http_tools on another kind": {withSource(func(r *SourceRule) { r.Kind = "rest" }), `sources[0].http_tools: is set only on a source of kind http`}, + } { + s.ErrorContains(test.manifest.Validate(), test.refusal, name) + } +} + +// Every rule is told apart by the field it names, so a manifest breaking several hears of each. +func (s *HTTPSourceSuite) TestEveryToolIsChecked() { + second := forecast() + second.Name, second.Method = "create_forecast", "POST" + + err := httpManifest(forecast(), second).Validate() + + s.ErrorContains(err, `http_tools[1].read_only: a read-only tool must be GET or HEAD, and "create_forecast" is POST`) + s.NotContains(err.Error(), "http_tools[0]") +} + +func (s *HTTPSourceSuite) TestAnHTTPSourceParsesFromYAML() { + parsed, err := ParseManifest(minimal("endpoints:\n http: https://api.example.com/v1\nsources:\n - kind: http\n endpoint: http\n" + + " http_tools:\n - name: get_forecast\n method: GET\n path: /forecast/{city}\n read_only: true\n" + + " parameters:\n city: {type: string, required: true}\n")) + s.Require().NoError(err) + + s.Equal([]HTTPTool{{Name: "get_forecast", Method: "GET", Path: "/forecast/{city}", ReadOnly: true, + Parameters: map[string]HTTPParameter{"city": {Type: "string", Required: true}}}}, HTTPSource(parsed.Sources).HTTPTools) +} + +// A read_only http tool is one its source does not send out, as a name in read_only_tools is +// for an mcp source; any other tool of it may. +func (s *HTTPSourceSuite) TestAReadOnlyHTTPToolSendsNothingOut() { + writes := forecast() + writes.Name, writes.Method, writes.ReadOnly = "create_forecast", "POST", false + m := httpManifest(forecast(), writes) + source := HTTPSource(m.Sources) + + s.False(source.SendsOutTool("get_forecast")) + s.True(source.SendsOutTool("create_forecast")) + s.True(source.SendsOutTool("unlisted")) + s.False(m.SendsOutTool("get_forecast")) + s.True(m.SendsOutTool("create_forecast")) +} + +// read_only is read from the connector's latest revision, so a revision changing only it reads +// as the one before; a changed method or path is what the connection sends, and reads otherwise. +func (s *HTTPSourceSuite) TestARevisionChangingOnlyReadOnlyReadsAsTheOneBefore() { + pinned := httpManifest(forecast()) + + s.True(pinned.ReadsAsConnection(withTool(func(t *HTTPTool) { t.ReadOnly = false }))) + s.False(pinned.ReadsAsConnection(withTool(func(t *HTTPTool) { t.Method = "HEAD" }))) + s.False(pinned.ReadsAsConnection(withTool(func(t *HTTPTool) { t.Path = "/forecasts/{city}" }))) + s.True(HTTPSource(pinned.Sources).HTTPTools[0].ReadOnly, "the comparison leaves the manifest as it was") +} diff --git a/acceleration/internal/connectors/core/manifest.go b/acceleration/internal/connectors/core/manifest.go index b1022af65b..cf22af1f97 100644 --- a/acceleration/internal/connectors/core/manifest.go +++ b/acceleration/internal/connectors/core/manifest.go @@ -119,8 +119,9 @@ type Manifest struct { // Those are the revision's own number; broken_revisions, which the seeder alone reads; // category, description and setup, which only the catalog shows, from the connector's latest // revision (connectorOf, internal/api/connectors.go); and sensitive and each source's outbound -// and read_only_tools, which only the sensitive-connector check and a connection's tools' -// read_only read, from the connector's latest revision whatever a connection pins +// and read_only_tools and each http tool's read_only, which only the sensitive-connector check +// and a connection's tools' read_only read, from the connector's latest revision whatever a +// connection pins // (SensitiveBindingsComplaint, internal/api/configs.go; listConnectionTools, // internal/api/connection_tools.go); and sandbox.reads, which a session reads from the connector's latest // revision (sandboxGrant, internal/session/sandbox_grants.go). Any other field counts, the name @@ -136,6 +137,10 @@ func (m Manifest) connectionReads() Manifest { m.Sources = slices.Clone(m.Sources) for i := range m.Sources { m.Sources[i].Outbound, m.Sources[i].ReadOnlyTools = nil, nil + m.Sources[i].HTTPTools = slices.Clone(m.Sources[i].HTTPTools) + for j := range m.Sources[i].HTTPTools { + m.Sources[i].HTTPTools[j].ReadOnly = false + } } if m.Sandbox != nil { sandbox := *m.Sandbox @@ -284,6 +289,10 @@ type SourceRule struct { // beside it in the manifest. A tool left out may write. Left out of the JSON when empty, // so the JSON of every manifest stored before it stays as it was. ReadOnlyTools []string `yaml:"read_only_tools,omitempty" json:"read_only_tools,omitempty"` + // HTTPTools are the tools an http source (SourceKindHTTP) offers: it has no server that lists + // them, so the manifest does. No other kind sets them. Left out of the JSON when empty, so + // the JSON of every manifest stored before it stays as it was. + HTTPTools []HTTPTool `yaml:"http_tools,omitempty" json:"http_tools,omitempty"` } // SendsOut reports whether a tool of the source may send data out of the conversation. @@ -292,9 +301,11 @@ func (r SourceRule) SendsOut() bool { } // SendsOutTool reports whether the source's tool called name may send data out of the -// conversation: unless the source says outbound: false or lists it in read_only_tools. +// conversation: unless the source says outbound: false, lists it in read_only_tools or has it +// as an http tool that says read_only. func (r SourceRule) SendsOutTool(name string) bool { - return r.SendsOut() && !slices.Contains(r.ReadOnlyTools, name) + return r.SendsOut() && !slices.Contains(r.ReadOnlyTools, name) && + !slices.ContainsFunc(r.HTTPTools, func(tool HTTPTool) bool { return tool.Name == name && tool.ReadOnly }) } // SendsOutTool reports whether a tool granted by the name name may send data out of the @@ -815,6 +826,11 @@ func (m Manifest) Validate() error { fail(field+".needs_scopes", "is required: a tool that needs no scope is left out") } } + if source.Kind == SourceKindHTTP { + checkHTTPSource(fail, field, source) + } else if len(source.HTTPTools) > 0 { + fail(field+".http_tools", "is set only on a source of kind %s", SourceKindHTTP) + } readOnly := map[string]bool{} for j, tool := range source.ReadOnlyTools { field := fmt.Sprintf("%s.read_only_tools[%d]", field, j) diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 7c62f3ed7e..fd1dab7d50 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -2416,6 +2416,32 @@ func (s *DataMoveSuite) TestAnImportedDefinitionWhoseServerIsNotHTTPSIsRefused() s.Zero(s.definitionsNamed(id)) } +// customWeather is a manifest the API stores for a custom http connector custom_weather: one +// read-only GET tool on an API taking a key. +const customWeather = `{"id": "custom_acme", "revision": 1, "name": "Weather", "endpoints": {"http": "https://api.weather.example/v1"}, + "schemes": ["api_key"], "sources": [{"kind": "http", "endpoint": "http", "http_tools": [{"name": "get_forecast", + "method": "GET", "path": "/forecast/{city}", "read_only": true, "parameters": {"city": {"type": "string", "required": true}}}]}]}` + +func (s *DataMoveSuite) TestAnImportedHTTPDefinitionArrivesAsItWasSent() { + id, err := s.importDefinition(customWeather) + + s.Require().NoError(err) + var stored string + s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, + "SELECT manifest FROM connector_definitions WHERE customer_id = 'moved' AND id = ?", id).Scan(&stored)) + s.JSONEq(strings.Replace(customWeather, "custom_acme", id, 1), stored) +} + +// TestAnImportedHTTPDefinitionWhoseReadOnlyToolWritesIsRefused: the http tool rules +// (core.Manifest.Validate) hold for an import as for the API. +func (s *DataMoveSuite) TestAnImportedHTTPDefinitionWhoseReadOnlyToolWritesIsRefused() { + id, err := s.importDefinition(strings.Replace(customWeather, `"method": "GET"`, `"method": "DELETE"`, 1)) + + s.ErrorIs(err, ErrNotACustomConnector) + s.ErrorContains(err, "a read-only tool must be GET or HEAD") + s.Zero(s.definitionsNamed(id)) +} + // TestALaterRevisionOfADefinitionImports: the store numbers revisions, so a manifest's own // revision is not one the API's rules set. func (s *DataMoveSuite) TestALaterRevisionOfADefinitionImports() { From 2a29dac4c8199893588b3b8872a9440088a59d86 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 01:11:15 +0100 Subject: [PATCH 02/13] [AI-3674] HTTP connectors: sources/http tool source (#2316) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Leaf 2 of 4 of AI-3669 (router runs http connectors). **Targets `feature/ai-3669-http-connectors`, not main.** No connector of kind `http` can be stored until the API leaf (AI-3676): the API takes none yet, and `POST /v1/data/import` now refuses one too (`importableDefinition`, `store/datamove.go`, until AI-3676 lifts it), so nothing changes for users yet. ## Why AI-3673 (#2303) taught core to describe an http connector: a `base_url` and tools, each with a method, a path, scalar parameters and `read_only`. Nothing could list or call those tools yet. Only `mcp` is in `Registry.ToolSources` (`cmd/router/main.go:556`). This PR adds the `http` tool source. Validate and the session already find each source by its kind (`sourceKinds`, `internal/api/connection_tools.go:785`, `internal/session/connector_tools.go:687`). ## How it works ``` Discover(binding) sends nothing: the manifest is the list for each sources[kind=http].http_tools[] input schema {type: object, properties: {p: {type, description}}, required: [...]} digest sha256(name, description, schema, method, path, read_only) Open(binding, grants) keep a tool granted by name AND digest unchanged offer as __ client copy of binding.HTTP, Timeout >= 35 s (as mcp) Call(name, arguments) ├─ unknown name / schema refuses -> error, nothing sent ├─ URL = base_url (one trailing / dropped) + path (text join) ├─ {p} -> url.PathEscape(value): one segment ├─ others ├─ GET, HEAD, DELETE -> query │ └─ POST, PUT, PATCH -> JSON object body ({} when none) │ only declared parameters; numbers as the model wrote them ├─ send through binding.HTTP (credential, 401 renewal, egress) └─ answer (read up to 4 MiB) ├─ 2xx -> text (non-UTF-8 -> "not text"), cut at 32 KiB └─ otherwise -> core.ToolError "The API answered [: body]" ``` | AI-3673 review requirement | Done here | Test | | --- | --- | --- | | R1.3: the pinned revision decides read_only | The digest covers method, path and read_only. A grant made for revision 2's read-only GET `x` never opens revision 1's POST `x`, and the reverse. | `TestSourceSuite/TestAGrantForAnotherRevisionOfAToolIsNeverOpened`, `TestTheDigestCoversEveryFieldOfTheTool` | | R1.4: parameter names that model APIs take | `~` is no longer allowed in a parameter name. The rule is now `^[A-Za-z0-9_.-]{1,64}$`, Anthropic's input_schema property-key pattern as its 400s quote it. A live probe was not possible: the provider keys we hold were refused. | `TestHTTPSourceSuite/TestAnHTTPSourceBreakingARuleIsRefused` ("a tilde") | ## Changes - New `internal/connectors/sources/http` (`source.go`, `toolset.go`, `AGENTS.md`, `CLAUDE.md`), modelled on `sources/mcp`. - `cmd/router/main.go` registers it beside mcp. - `core/http_tools.go`: the parameter-name rule as above, and a new rule: `sources[].tools` (the `needs_scopes` rules) is refused on an http source, which reads none (`leftOutGrant` reads only the mcp source). Left for AI-3675 (call-time safety), as `sources/http/AGENTS.md` lists: refusing an undeclared argument before sending (it is dropped today), refusing a `.` or `..` path value, override names at Open, redirect rules beyond egress's, and redacting arguments from log lines. ## Validation | Change | Test that fails without it | | --- | --- | | Source contract (digest, grants, schema check, 32 KiB cut, tool error) | `TestHTTPSourceContract` (`core/contracttest.SourceContract`) | | GET: path parameter in the path (escaped), the others in the query, a left-out one not sent, source header and bearer on it | `TestAGETSendsItsPathParameterInThePathAndTheOthersInTheQuery` | | POST: JSON body, 2^53+1 kept exact | `TestAPOSTSendsItsOtherParametersAsAJSONBody` | | Where each of the six methods sends a parameter; `{}` when none | `TestEachMethodSendsItsParametersWhereTheRuleSays` | | Text join, not `ResolveReference`; no doubled `/`; no empty `?` | `TestTheEndpointsOwnPathIsKeptAndItsTrailingSlashNotDoubled`, `TestNoArgumentsAtAllAreAnEmptyObject` | | 2xx bounds (299 ok, 300 error), status and body in the tool error, error cut | `TestAnAnswerThatIsNotA2xxIsAToolErrorNamingItsStatus`, `TestAToolErrorOverTheCapIsCutWithTheMarker` | | 4 MiB read cap, binary body, a body cut short | `TestABodyIsReadOnlyUpToTheCap`, `TestABodyThatIsNotTextReadsAsNotText`, `TestABodyCutShortIsAnErrorNotAnAnswer` | | Timeouts: toolset client >= 35 s, a longer one kept, `Binding.Timeout` bounds a call | `TestAnOpenedToolsetWaitsPastTheConnectionsClientTimeout`, `TestAClientWaitingLongerThanCallTimeoutKeepsItsTimeout`, `TestTheBindingsTimeoutBoundsACall` | | Registered by kind | `cmd/router` `TestConnectorRegistrySuite/TestWithConnectorsOnBothToolSourcesAreRegisteredByKind` | The tests ran on the branch at the feature-branch head 7d1d6b77c: `go test ./internal/connectors/... ./cmd/router/ ./internal/store/`, `go test -race ./internal/connectors/sources/http`, `go vet ./...` and `go vet -tags integration ./...`. One batched script applied 46 mutants, one per added guard, constant and digest field, and all 46 were killed. The guards no input can reach (marshal and compile errors of values the source builds itself, and a 1xx final status) are listed in the review notes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- acceleration/cmd/router/connectors_test.go | 15 + acceleration/cmd/router/main.go | 3 +- .../internal/connectors/core/AGENTS.md | 4 +- .../connectors/core/contracttest/AGENTS.md | 2 +- .../internal/connectors/core/http_tools.go | 21 +- .../connectors/core/http_tools_test.go | 9 +- .../internal/connectors/core/manifest.go | 4 + .../internal/connectors/core/provider_text.go | 12 +- .../connectors/core/provider_text_test.go | 9 + .../internal/connectors/core/source.go | 19 + .../connectors/sources/http/AGENTS.md | 54 ++ .../connectors/sources/http/CLAUDE.md | 1 + .../connectors/sources/http/source.go | 206 +++++ .../connectors/sources/http/source_test.go | 706 ++++++++++++++++++ .../connectors/sources/http/toolset.go | 201 +++++ acceleration/internal/store/datamove.go | 6 + acceleration/internal/store/datamove_test.go | 12 +- .../internal/store/datamove_unit_test.go | 41 + 18 files changed, 1303 insertions(+), 22 deletions(-) create mode 100644 acceleration/internal/connectors/sources/http/AGENTS.md create mode 100644 acceleration/internal/connectors/sources/http/CLAUDE.md create mode 100644 acceleration/internal/connectors/sources/http/source.go create mode 100644 acceleration/internal/connectors/sources/http/source_test.go create mode 100644 acceleration/internal/connectors/sources/http/toolset.go create mode 100644 acceleration/internal/store/datamove_unit_test.go diff --git a/acceleration/cmd/router/connectors_test.go b/acceleration/cmd/router/connectors_test.go index 5a7043f544..949d5f5356 100644 --- a/acceleration/cmd/router/connectors_test.go +++ b/acceleration/cmd/router/connectors_test.go @@ -67,6 +67,21 @@ func (s *ConnectorRegistrySuite) TestWithConnectorsOnEveryVerifierIsRegisteredBy s.Len(registry.Verifiers, 3) } +// AI-3674: a manifest's sources[].kind names mcp or http, and validate and a session find each +// source by it (sourceKinds, internal/api/connection_tools.go and internal/session). +func (s *ConnectorRegistrySuite) TestWithConnectorsOnBothToolSourcesAreRegisteredByKind() { + s.settings.Connectors.Enabled = true + + registry, err := newConnectorRegistry(s.settings, nil) + + s.Require().NoError(err) + for _, kind := range []string{core.SourceKindMCP, core.SourceKindHTTP} { + s.Require().Contains(registry.ToolSources, kind) + s.Equal(kind, registry.ToolSources[kind].Kind()) + } + s.Len(registry.ToolSources, 2) +} + func (s *ConnectorRegistrySuite) TestWithConnectorsOffNoVerifierIsRegistered() { registry, err := newConnectorRegistry(s.settings, nil) diff --git a/acceleration/cmd/router/main.go b/acceleration/cmd/router/main.go index 6a5ac25aa1..80467d588a 100644 --- a/acceleration/cmd/router/main.go +++ b/acceleration/cmd/router/main.go @@ -48,6 +48,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/oauth2cc" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/oauth2code" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/slackapps" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/mcp" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/verifiers/ed25519header" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/verifiers/hmacheader" @@ -553,7 +554,7 @@ func newConnectorRegistry(settings config.Config, clients oauth2code.ClientLooku } // The tool sources a manifest's sources[].kind may name; a new one is one more entry. sources := map[string]core.ToolSource{} - for _, source := range []core.ToolSource{mcp.New()} { + for _, source := range []core.ToolSource{mcp.New(), httpsource.New()} { sources[source.Kind()] = source } return core.Registry{Schemes: schemes, Verifiers: verifiers, ToolSources: sources}, nil diff --git a/acceleration/internal/connectors/core/AGENTS.md b/acceleration/internal/connectors/core/AGENTS.md index 41a80c1567..1079219095 100644 --- a/acceleration/internal/connectors/core/AGENTS.md +++ b/acceleration/internal/connectors/core/AGENTS.md @@ -24,7 +24,7 @@ One word, one meaning, in code, docs and API alike. A name follows the Go auth l | binding | What one agent config may use from one connector: which connection, and the exact tool grants | `Binding` with `Selection` `fixed` or `session`, `ToolGrant` (`source.go`), agent config `connectors[]` | `Selection` matches the API schema `AgentConnectorSelection`: it says how the connection is chosen, not what kind it is | | resolved binding | One binding resolved against one connection, with the connection's transport | `ResolvedBinding` (`source.go`), `ResolvedBinding.HTTP` | As resolved manifest | | transport | The outbound HTTP client of one connection: the egress client, with the connection's scheme applying a freshly resolved access credential to each request | `Transports.Client(ref, scheme)` (`transport.go`) | The spec's name for it (subtasks T13). Not "client", which is the OAuth client (`client registration`, `oauth2code.Client`) | -| tool source, toolset | What discovers and runs one kind of tools, and the tools it opened for one session | `ToolSource`, `Toolset` (`source.go`), `Registry.ToolSources`, `sources/mcp` | Pydantic AI `AbstractToolset`, Google ADK toolsets. Not `Source` or `Runtime` | +| tool source, toolset | What discovers and runs one kind of tools, and the tools it opened for one session | `ToolSource`, `Toolset` (`source.go`), `Registry.ToolSources`, `sources/mcp`, `sources/http` | Pydantic AI `AbstractToolset`, Google ADK toolsets. Not `Source` or `Runtime` | | event source, event subscription | A tool source whose server also delivers events to a webhook the router serves, and one event, with its filters, delivered to one URL signed with one secret the client supplies | `EventSource`, `EventSubscription`, `EventGrant`, `ErrNoEvents` (`source.go`), `sources/mcp`; the caller is `internal/mcpevents` | MCP Events, a draft: experimental-ext-triggers-events at `6682596d`, «Webhook-Based Delivery» | | needs scopes | The scopes a call of one tool needs, which validate compares with the connection's granted scopes. A tool that needs a scope `scopes.list` does not hold is never asked for at consent, so the source leaves it out (AI-1394) | manifest `sources[].tools[].needs_scopes`, `ToolRule`, `ToolSpec.NeedsScopes` | Architecture doc, stress-test row 12 and «Add» item 11 | | covered by | For a scope a tool needs, the broader scopes the provider documents as giving all it gives; holding one meets the need | manifest `scopes.covered_by`, `ScopePolicy.CoveredBy`, `ScopePolicy.Meets` | Says what it is | @@ -55,7 +55,7 @@ A manifest has `sources`, a `channel` block, or both: Linear has only `sources`, `sensitive: true` marks a connector that reads private data, and `sources[].outbound: false` says a source offers only tools that read, and `sources[].read_only_tools` names the ones that read on a source that also offers tools that write; left out, a tool may write and counts as sending data out. A config binding a sensitive connector is refused beside any binding granting a tool that may send out (`providers/AGENTS.md`, `sensitiveBindingsComplaint`). -A source of kind `http` (`SourceKindHTTP`, `http_tools.go`) lists its own tools in `sources[].http_tools`: each a name, a description, a method, a path under the source's endpoint with `{name}` placeholders, scalar `parameters` and `read_only`. `read_only` is allowed only on GET and HEAD, and it is where an http source says a tool only reads: `read_only_tools` and `outbound: false` are refused on one. A parameter or source header named as a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method`, in any case) is refused, so a read-only GET cannot be run as a write. A custom connector is an MCP endpoint or an http `base_url` with tools (`CustomManifest`), under the endpoint role `http`. No source runs http tools yet. +A source of kind `http` (`SourceKindHTTP`, `http_tools.go`) lists its own tools in `sources[].http_tools`: each a name, a description, a method, a path under the source's endpoint with `{name}` placeholders, scalar `parameters` and `read_only`. `read_only` is allowed only on GET and HEAD, and it is where an http source says a tool only reads: `read_only_tools` and `outbound: false` are refused on one, and so is `sources[].tools` (`needs_scopes`), which an http source never reads. A manifest has at most one http source, as only the first is read (`HTTPSource`). A parameter or source header named as a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method`, in any case) is refused, so a read-only GET cannot be run as a write. A custom connector is an MCP endpoint or an http `base_url` with tools (`CustomManifest`), under the endpoint role `http`. `sources/http` runs its tools. | Term | What it is | In code | | --- | --- | --- | diff --git a/acceleration/internal/connectors/core/contracttest/AGENTS.md b/acceleration/internal/connectors/core/contracttest/AGENTS.md index d6860018bb..6841fb70c2 100644 --- a/acceleration/internal/connectors/core/contracttest/AGENTS.md +++ b/acceleration/internal/connectors/core/contracttest/AGENTS.md @@ -15,7 +15,7 @@ The subject runs a provider offering three tools: `ToolEcho` (`{"text": string}` | `TestAResultOverTheCapIsCutWithTheMarker` | A long result fits `core.MaxResultBytes`, ends with `core.TruncatedMarker` and is valid UTF-8 | | `TestAnErrorWithNoTextIsStillAnError` | A tool's own failure is a `*core.ToolError`, even with no text | -A new source adopts it with one test function, as `sources/mcp/source_test.go` (`TestMCPSourceContract`) does. +A new source adopts it with one test function, as `sources/mcp/source_test.go` (`TestMCPSourceContract`) and `sources/http/source_test.go` (`TestHTTPSourceContract`) do. ## What `SchemeContract` proves diff --git a/acceleration/internal/connectors/core/http_tools.go b/acceleration/internal/connectors/core/http_tools.go index 5440a9f3d5..208a523c9d 100644 --- a/acceleration/internal/connectors/core/http_tools.go +++ b/acceleration/internal/connectors/core/http_tools.go @@ -62,9 +62,6 @@ const ( // maxHTTPParameters is the cap an agent config has on its connector bindings and its // visible_tools (internal/api/configs.go). maxHTTPParameters = 64 - // maxHTTPParameterName is the length OpenAI caps a function name at - // (https://developers.openai.com/api/reference/resources/chat, tools[].function.name). - maxHTTPParameterName = 64 ) var ( @@ -88,12 +85,19 @@ var ( // (AgentConnectorBinding.name, internal/api/configs.go), and 63+2+63 is the 128 Anthropic // caps a tool name at (^[a-zA-Z0-9_-]{1,128}$, // https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools). OpenAI caps - // a function name at 64 (the reference maxHTTPParameterName cites), so a longest alias and - // name do not fit it: the same holds for an MCP tool today. + // a function name at 64 (https://developers.openai.com/api/reference/resources/chat, + // tools[].function.name), so a longest alias and name do not fit it: the same holds for an + // MCP tool today. httpToolName = regexp.MustCompile(`^[A-Za-z0-9_-]{1,63}$`) // httpPath is visible ASCII (RFC 9110 section 5.5's vchar), so a path holds no space or // line break, and no ? or #, so it has no query or fragment of its own. httpPath = regexp.MustCompile(`^/[!"$->@-~]*$`) + // httpParameterName is what Anthropic takes as a key of a tool's input_schema properties, + // 1 to 64 letters, digits, _, . or -: its 400 answers a key outside it with «Property keys + // should match pattern '^[a-zA-Z0-9_.-]{1,64}$'» (quoted in anthropics/claude-code issues + // 24272, 34771 and 92648; not probed live, AI-3674: the keys in .env were refused). Each of + // these characters is RFC 3986 unreserved, so a name also goes into a query as it is. + httpParameterName = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,64}$`) ) // checkHTTPSource refuses an http source whose tools a session could not offer or that could @@ -102,6 +106,9 @@ func checkHTTPSource(fail func(field, format string, args ...any), field string, if len(source.ReadOnlyTools) > 0 { fail(field+".read_only_tools", "is not set on an http source: each of its tools says read_only") } + if len(source.Tools) > 0 { + fail(field+".tools", "is not set on an http source: it reads no needs_scopes, and a tool of http_tools needs none") + } if !source.SendsOut() { fail(field+".outbound", "is not false on an http source: each of its tools says read_only") } @@ -139,8 +146,8 @@ func checkHTTPSource(fail func(field, format string, args ...any), field string, for _, name := range slices.Sorted(maps.Keys(tool.Parameters)) { field := field + ".parameters." + name switch { - case len(name) > maxHTTPParameterName || !unreserved.MatchString(name): - fail(field, "%q is not 1 to %d letters, digits, ., _, ~ or -", name, maxHTTPParameterName) + case !httpParameterName.MatchString(name): + fail(field, "%q is not 1 to 64 letters, digits, ., _ or -", name) case slices.Contains(httpMethodOverrides, strings.ToLower(name)): fail(field, "names a method override") } diff --git a/acceleration/internal/connectors/core/http_tools_test.go b/acceleration/internal/connectors/core/http_tools_test.go index b27df640fe..5ab0f320db 100644 --- a/acceleration/internal/connectors/core/http_tools_test.go +++ b/acceleration/internal/connectors/core/http_tools_test.go @@ -87,11 +87,10 @@ func (s *HTTPSourceSuite) TestAValidHTTPSourceIsAccepted() { "an escaped and a reserved character": withTool(func(t *HTTPTool) { t.Path = "/a%20b/c:d;e=f@g!$&'()*+,/{city}" }), "128 tools": httpManifest(tools(128)...), "64 parameters": withTool(func(t *HTTPTool) { t.Parameters = parameters(64) }), - "a parameter of 64 with . ~ and -": withTool(func(t *HTTPTool) { t.Parameters["a.b~c-"+strings.Repeat("d", 58)] = HTTPParameter{Type: "string"} }), + "a parameter of 64 with . _ and -": withTool(func(t *HTTPTool) { t.Parameters["a.b_c-"+strings.Repeat("d", 58)] = HTTPParameter{Type: "string"} }), "a parameter merely holding method": withTool(func(t *HTTPTool) { t.Parameters["http_method_name"] = HTTPParameter{Type: "string"} }), "a header that is no override": withSource(func(r *SourceRule) { r.Headers = map[string]string{"X-Api-Version": "2"} }), "outbound true": withSource(func(r *SourceRule) { r.Outbound = new(true) }), - "needs_scopes for one of its tools": withSource(func(r *SourceRule) { r.Tools = []ToolRule{{Name: "get_forecast", NeedsScopes: []string{"read"}}} }), "an mcp source with an override header": {ID: "example", Revision: 1, Name: "Example", Schemes: []string{"bearer"}, Endpoints: map[string]string{SourceKindMCP: "https://api.example.com/mcp"}, Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP, Headers: map[string]string{"X-HTTP-Method-Override": "POST"}}}}, @@ -145,6 +144,8 @@ func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { "x-http-method": {withTool(func(t *HTTPTool) { t.Parameters["x-http-method"] = HTTPParameter{Type: "string"} }), `parameters.x-http-method: names a method override`}, "X-Method-Override": {withTool(func(t *HTTPTool) { t.Parameters["X-Method-Override"] = HTTPParameter{Type: "string"} }), `parameters.X-Method-Override: names a method override`}, "$httpMethod": {withTool(func(t *HTTPTool) { t.Parameters["$httpMethod"] = HTTPParameter{Type: "string"} }), `parameters.$httpMethod: "$httpMethod" is not 1 to 64`}, + "a tilde": {withTool(func(t *HTTPTool) { t.Parameters["a~b"] = HTTPParameter{Type: "string"} }), `parameters.a~b: "a~b" is not 1 to 64 letters, digits, ., _ or -`}, + "a slash": {withTool(func(t *HTTPTool) { t.Parameters["a/b"] = HTTPParameter{Type: "string"} }), `parameters.a/b: "a/b" is not 1 to 64`}, "a bracket": {withTool(func(t *HTTPTool) { t.Parameters["page[size]"] = HTTPParameter{Type: "string"} }), `"page[size]" is not 1 to 64`}, "a brace": {withTool(func(t *HTTPTool) { t.Parameters["a}b"] = HTTPParameter{Type: "string"} }), `"a}b" is not 1 to 64`}, "an empty name": {withTool(func(t *HTTPTool) { t.Parameters[""] = HTTPParameter{Type: "string"} }), `"" is not 1 to 64`}, @@ -153,6 +154,7 @@ func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { "an override header": {withSource(func(r *SourceRule) { r.Headers = map[string]string{"x-HTTP-method-OVERRIDE": "POST"} }), `sources[0].headers.x-HTTP-method-OVERRIDE: names a method override`}, "read_only_tools": {withSource(func(r *SourceRule) { r.ReadOnlyTools = []string{"get_forecast"} }), `sources[0].read_only_tools: is not set on an http source`}, + "needs_scopes": {withSource(func(r *SourceRule) { r.Tools = []ToolRule{{Name: "get_forecast", NeedsScopes: []string{"read"}}} }), `sources[0].tools: is not set on an http source`}, "outbound false": {withSource(func(r *SourceRule) { r.Outbound = new(false) }), `sources[0].outbound: is not false on an http source`}, "no tool name": {withTool(func(t *HTTPTool) { t.Name = "" }), `http_tools[0].name: "" is not 1 to 63 letters, digits, _ or -`}, "a dot": {withTool(func(t *HTTPTool) { t.Name = "forecast.get" }), `"forecast.get" is not 1 to 63`}, @@ -161,6 +163,7 @@ func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { "a name twice": {httpManifest(forecast(), forecast()), `http_tools[1].name: "get_forecast" is named twice`}, "a description of 1001 bytes in 501 characters": {withTool(func(t *HTTPTool) { t.Description = strings.Repeat("é", 500) + "d" }), `http_tools[0].description: is over 1000 bytes`}, "outbound false on a source with no tool": {noTool(func(r *SourceRule) { r.Outbound = new(false) }), `sources[0].outbound: is not false on an http source`}, + "needs_scopes on a source with no tool": {noTool(func(r *SourceRule) { r.Tools = []ToolRule{{Name: "x", NeedsScopes: []string{"read"}}} }), `sources[0].tools: is not set on an http source`}, "read_only_tools on a source with no tool": {noTool(func(r *SourceRule) { r.ReadOnlyTools = []string{"x"} }), `sources[0].read_only_tools: is not set on an http source`}, "an override header on a source with no tool": {noTool(func(r *SourceRule) { r.Headers = map[string]string{"X-HTTP-Method": "PUT"} }), `names a method override`}, "a description over 1000": {withTool(func(t *HTTPTool) { t.Description = strings.Repeat("d", 1001) }), `http_tools[0].description: is over 1000 bytes`}, @@ -169,6 +172,8 @@ func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { Endpoints: map[string]string{SourceKindMCP: "https://api.example.com/mcp"}, Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP, HTTPTools: []HTTPTool{forecast()}}}}, `sources[0].http_tools: is set only on a source of kind http`}, + "a second http source": {func() Manifest { m := httpManifest(forecast()); m.Sources = append(m.Sources, m.Sources[0]); return m }(), + `sources[1].kind: is http a second time`}, "http_tools on another kind": {withSource(func(r *SourceRule) { r.Kind = "rest" }), `sources[0].http_tools: is set only on a source of kind http`}, } { s.ErrorContains(test.manifest.Validate(), test.refusal, name) diff --git a/acceleration/internal/connectors/core/manifest.go b/acceleration/internal/connectors/core/manifest.go index cf22af1f97..cc5b0ab84e 100644 --- a/acceleration/internal/connectors/core/manifest.go +++ b/acceleration/internal/connectors/core/manifest.go @@ -827,6 +827,10 @@ func (m Manifest) Validate() error { } } if source.Kind == SourceKindHTTP { + // The http source reads only the first one (HTTPSource), as the mcp source does. + if HTTPSource(m.Sources) != &m.Sources[i] { + fail(field+".kind", "is http a second time: a manifest has at most one http source") + } checkHTTPSource(fail, field, source) } else if len(source.HTTPTools) > 0 { fail(field+".http_tools", "is set only on a source of kind %s", SourceKindHTTP) diff --git a/acceleration/internal/connectors/core/provider_text.go b/acceleration/internal/connectors/core/provider_text.go index 87f55c72a6..1a0174540d 100644 --- a/acceleration/internal/connectors/core/provider_text.go +++ b/acceleration/internal/connectors/core/provider_text.go @@ -1,6 +1,7 @@ package core import ( + "errors" "net/url" "regexp" "unicode/utf8" @@ -30,8 +31,8 @@ const MessageBytes = 1 << 10 // LoggedMessage is what err, the error a failed call returned, says, for its log line: the // tool's own words for an MCP isError (ToolError, whose Error is its Message), the SDK's -// or the JSON-RPC error's text, or the refusal's reason (session's dispatcher.recheck). Empty -// for nil. +// or the JSON-RPC error's text, or the refusal's reason (session's dispatcher.recheck), and +// for an UnreachedError its Message followed by its Err's text. Empty for nil. // // Every http or https URL in it keeps only its scheme and host, since its userinfo, path or // query can carry a token. The text is searched rather than a *url.Error unwrapped: the MCP @@ -52,7 +53,12 @@ func LoggedMessage(err error, redact func(string) string) string { if err == nil { return "" } - text := KeepHosts(err.Error()) + text := err.Error() + // What an UnreachedError hides from the model is what the line is for. + if unreached, ok := errors.AsType[*UnreachedError](err); ok && unreached.Err != nil { + text += ": " + unreached.Err.Error() + } + text = KeepHosts(text) if redact != nil { text = redact(text) } diff --git a/acceleration/internal/connectors/core/provider_text_test.go b/acceleration/internal/connectors/core/provider_text_test.go index 148082be7d..a046c34fa4 100644 --- a/acceleration/internal/connectors/core/provider_text_test.go +++ b/acceleration/internal/connectors/core/provider_text_test.go @@ -93,6 +93,15 @@ func (s *LoggedMessageSuite) TestAToolErrorIsTheToolsOwnWords() { s.Equal("the record is locked", core.LoggedMessage(err, nil)) } +// S1.1 of AI-3674: what an UnreachedError keeps from the model is on the line, its URL kept to +// its host as any other's. +func (s *LoggedMessageSuite) TestAnUnreachedErrorAddsWhatFailed() { + sending := &url.Error{Op: "Get", URL: "https://crm.example/people/u1?email=alice%40example.com", Err: io.EOF} + err := stack.Wrap(&core.UnreachedError{Message: "http: crm__lookup: the API could not be reached", Err: sending}) + + s.Equal(`http: crm__lookup: the API could not be reached: Get "https://crm.example": EOF`, core.LoggedMessage(err, nil)) +} + func (s *LoggedMessageSuite) TestNoErrorIsNoMessage() { s.Empty(core.LoggedMessage(nil, nil)) } diff --git a/acceleration/internal/connectors/core/source.go b/acceleration/internal/connectors/core/source.go index a7bf11deb6..82137f920c 100644 --- a/acceleration/internal/connectors/core/source.go +++ b/acceleration/internal/connectors/core/source.go @@ -111,6 +111,25 @@ func (e *ToolError) Error() string { return e.Message } +// UnreachedError is a call that got no whole answer to read: the request could not be sent, the +// egress policy refused where it went, or the answer stopped part way. Its Error is Message, one +// fixed sentence the model reads, since Err, what failed, names the request's URL with the +// model's arguments in it and the egress policy's or the resolver's words, which tell a private +// host from one that does not resolve. Err stays behind Unwrap, for errors.Is, and goes on the +// call's log line (LoggedMessage). +type UnreachedError struct { + Message string + Err error +} + +func (e *UnreachedError) Error() string { + return e.Message +} + +func (e *UnreachedError) Unwrap() error { + return e.Err +} + // ResolvedBinding is one binding resolved against one connection. type ResolvedBinding struct { Binding Binding diff --git a/acceleration/internal/connectors/sources/http/AGENTS.md b/acceleration/internal/connectors/sources/http/AGENTS.md new file mode 100644 index 0000000000..1d50b03ce1 --- /dev/null +++ b/acceleration/internal/connectors/sources/http/AGENTS.md @@ -0,0 +1,54 @@ +# internal/connectors/sources/http + +The `core.ToolSource` for a connector whose manifest lists its own tools, registered as `http` (`Kind`, `core.SourceKindHTTP`), the name a manifest's `sources[].kind` gives it. Each tool in `sources[].http_tools` (`core.HTTPTool`, validated in `core/http_tools.go`) is one HTTP request to the source's endpoint. Callers, through `core.Registry.ToolSources` (`cmd/router/main.go`): `POST /v1/agents/connections/{id}/validate` (`Discover`, `internal/api/connection_tools.go`) and the session (`Open`, `internal/session/connector_tools.go`), whose dispatcher runs `Toolset.Call` and bounds it itself. No stored connector has kind `http` until the API takes one (AI-3676): an import refuses one too (`importableDefinition`, `internal/store/datamove.go`) until then. + +## Flow + +``` +Discover(ctx, binding) sends nothing: the manifest is the list + source manifest sources[kind=http], its endpoint -> Endpoints[role] + ToolSpec name, description, + input schema {type: object, properties: {: {type, description}}, + required: []} + SchemaDigest = sha256(name, description, input schema, method, path, read_only) + +Open(ctx, binding, grants) + alias binding.Name, never holding "__" + client a copy of binding.HTTP whose Timeout is at least 35 s (callTimeout) + keep granted by name AND digest unchanged + offer alias + "__" + name + +Toolset.Call(call) + unknown name -> error, nothing sent + arguments vs schema -> error, nothing sent + URL endpoint (one trailing / dropped) + path, joined as text + {name} the argument, url.PathEscape'd: one segment + others GET, HEAD, DELETE -> query; POST, PUT, PATCH -> JSON object body + (an empty object when every parameter is in the path) + only declared parameters; numbers as the model wrote them + headers sources[].headers, then the connection's transport adds the credential + no answer not sent, refused by egress, or cut short -> *core.UnreachedError: one sentence + "http: : the API could not be reached, or its answer did not arrive whole"; + the cause behind Unwrap and on the log line (core.LoggedMessage) + answer read up to 4 MiB, cut back to a whole rune; not UTF-8 -> "not text" sentence + 2xx text, cut at 32 KiB + marker (core.CutResult); empty -> "The API answered ." + otherwise *core.ToolError "The API answered [: ]", cut the same way +``` + +## Rules + +- **Only through `ResolvedBinding.HTTP`.** The source never builds a client: an opened toolset sends with a copy of the binding's client that differs only in its timeout, so the credential, the 401 renewal (`core/AGENTS.md`, «Transport»), the egress checks and the redirect policy all run. Check: `go test -run 'TestSourceSuite/(TestAGETSends|TestAnAnswerThatIsNotA2xx)' ./internal/connectors/sources/http`. +- **Where a parameter goes is decided (AI-3669, «Decided»).** `{name}` in the path, escaped as one segment; the others in the query of a GET, a HEAD or a DELETE, and in a JSON body of a POST, a PUT or a PATCH. Only the parameters the tool declares are sent, so an argument the model adds goes nowhere. Check: `go test -run 'TestSourceSuite/(TestAGETSends|TestAPOSTSends|TestEachMethod|TestAnArgumentTheTool)' ./internal/connectors/sources/http`. +- **The endpoint and the path are joined as text.** Never `url.ResolveReference`, which drops the endpoint's own path for a path starting with `/`; `core.Manifest.Validate` refuses a path starting with `//` or holding `\`. Check: `go test -run 'TestSourceSuite/TestTheEndpointsOwnPath' ./internal/connectors/sources/http`. +- **A tool is offered only when its grant names it and pins the digest it has now.** The digest covers method, path and read_only beside what the model is shown, so a revision that turns a POST into a read-only GET is a new digest, and a connection pinned to one revision never runs a tool under a grant made for the other (AI-3674, from the AI-3673 review). Check: `go test -run 'TestHTTPSourceContract/(TestOnlyTheGranted|TestAnUngranted|TestAToolWhoseSchema)|TestSourceSuite/(TestAGrantForAnotherRevision|TestTheDigestCovers)' ./internal/connectors/sources/http`. +- **Arguments are checked before anything is sent**, against the schema built from the declared parameters (JSON Schema 2020-12). Check: `go test -run 'TestHTTPSourceContract/TestArguments' ./internal/connectors/sources/http`. +- **An answer that is not a 2xx is a `*core.ToolError`** naming the status, with the API's words when it said any. Check: `go test -run 'TestHTTPSourceContract/TestAnErrorWithNoText|TestSourceSuite/(TestAnAnswerThatIsNotA2xx|TestAToolErrorOverTheCap)' ./internal/connectors/sources/http`. +- **A call that got no whole answer reads one sentence.** The model never reads the request's URL, an argument, or what the egress policy or the resolver said, which would tell a private host from one that does not resolve (AI-3674, S1.1). Check: `go test -run 'TestSourceSuite/(TestACallThatReachesNoAPI|TestABodyCutShort)' ./internal/connectors/sources/http`. +- **Bounded.** One body is read up to 4 MiB (`maxResponseBytes`, the mcp source's cap); one result or tool error is at most `core.MaxResultBytes` (32 KiB), ending with `core.TruncatedMarker`. An opened toolset's client waits at least `callTimeout` (35 s), past the longest `timeout_ms` a binding may ask for (30 s), and `Binding.Timeout` bounds a call when set. Check: `go test -run 'TestHTTPSourceContract/TestAResultOverTheCap|TestSourceSuite/(TestABodyIsRead|TestAnOpenedToolsetWaits|TestTheBindingsTimeout)' ./internal/connectors/sources/http`. +- **Every hardcoded value says where it comes from**, beside it: `Separator`, `defaultCallTimeout`, `maxResponseBytes`, `nonText`, `bodyMethods`. + +Not here yet (AI-3675, call-time safety): refusing an undeclared argument before sending (today it is dropped), refusing a `.` or `..` path value, refusing an override name at `Open`, redirect rules beyond egress's, and redacting arguments from log lines. A manifest that sets `sources[].tools` (the `needs_scopes` rules) on an http source is refused (`checkHTTPSource`), as the source reads none: no tool is left out for a scope and validate reports none. + +## Tests + +From `acceleration/`: `go test -race ./internal/connectors/sources/http`. `TestHTTPSourceContract` runs `core/contracttest.SourceContract`; `SourceSuite` the rest. The provider is a loopback TLS server that takes one bearer token, records each request and answers by path, reached through `core.Transports` with the `bearer` scheme. No mocks (`.claude/skills/go-testing/SKILL.md`). diff --git a/acceleration/internal/connectors/sources/http/CLAUDE.md b/acceleration/internal/connectors/sources/http/CLAUDE.md new file mode 100644 index 0000000000..43c994c2d3 --- /dev/null +++ b/acceleration/internal/connectors/sources/http/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/acceleration/internal/connectors/sources/http/source.go b/acceleration/internal/connectors/sources/http/source.go new file mode 100644 index 0000000000..548c5c527e --- /dev/null +++ b/acceleration/internal/connectors/sources/http/source.go @@ -0,0 +1,206 @@ +// Package http is the core.ToolSource for a connector whose manifest lists its own tools, each +// one HTTP request to the connector's API (core.SourceKindHTTP). It builds each tool's input +// schema from the parameters the manifest declares, and sends a granted tool's request through +// the connection's own client (core.ResolvedBinding.HTTP), which applies its credential and the +// egress policy. +package http + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "maps" + "net/http" + "slices" + "strings" + "time" + + "github.com/santhosh-tekuri/jsonschema/v6" + + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/mcp" + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" +) + +// Kind is the name a manifest's sources[].kind gives this source, and its key in +// core.Registry.ToolSources. +const Kind = core.SourceKindHTTP + +// Separator joins a binding's alias and a tool's name into the name the model is offered: the +// mcp source's, at which the session splits every connector tool's name back +// (internal/session/connector_tools.go). +const Separator = mcp.Separator + +// defaultCallTimeout is the least timeout the client of an opened Toolset has, for the same +// reason as the mcp source's (mcp.defaultCallTimeout): longer than the longest call a binding may +// ask for (30 s, api.AgentConnectorBinding.TimeoutMs), so the caller's deadline ends a call +// first, and the client the router builds for a connection cuts a request at 10 s +// (connectorHTTPTimeout, cmd/router/main.go). The 5 s above 30 s is a margin, a choice: +// unverified. +const defaultCallTimeout = 35 * time.Second + +// schemaLocation is the URL each tool's input schema is compiled under. .invalid is reserved and +// never resolves (RFC 6761 section 6.4); a schema built from scalar parameters refers to nothing. +const schemaLocation = "https://vision-agents.invalid/http-tool-schema.json" + +// Source is the http core.ToolSource. It holds no state, so one serves every connection. +type Source struct { + callTimeout time.Duration +} + +var _ core.ToolSource = (*Source)(nil) + +// New is the http source. +func New() *Source { + return &Source{callTimeout: defaultCallTimeout} +} + +// Kind is Kind. +func (*Source) Kind() string { + return Kind +} + +// Discover is every tool the manifest's http source lists, each with its input schema and its +// digest. It sends nothing: the manifest is the list. +func (*Source) Discover(_ context.Context, b core.ResolvedBinding) ([]core.ToolSpec, error) { + rule, _, err := httpSource(b) + if err != nil { + return nil, err + } + specs := make([]core.ToolSpec, 0, len(rule.HTTPTools)) + for _, tool := range rule.HTTPTools { + digest, err := ToolSchemaDigest(tool) + if err != nil { + return nil, err + } + specs = append(specs, core.ToolSpec{Name: tool.Name, Description: tool.Description, + InputSchema: inputSchema(tool), SchemaDigest: digest}) + } + return specs, nil +} + +// Open keeps the granted tools whose digest still matches the grant, each offered to the model +// as the binding's alias, Separator and its name. A tool not granted, or whose definition +// changed since it was granted, is not offered and never called. +// +// The alias must not hold Separator, so the name a model calls splits back into one alias and +// one tool: two bindings cannot offer the same name. +func (s *Source) Open(_ context.Context, b core.ResolvedBinding, grants []core.ToolGrant) (core.Toolset, error) { + alias := b.Binding.Name + if alias == "" || strings.Contains(alias, Separator) { + return nil, stack.Wrap(fmt.Errorf("http: binding name %q must be set and must not hold %q", alias, Separator)) + } + if b.HTTP == nil { + return nil, stack.Wrap(errors.New("http: the binding has no client: build it with core.Transports")) + } + rule, endpoint, err := httpSource(b) + if err != nil { + return nil, err + } + granted := make(map[string]string, len(grants)) + for _, grant := range grants { + granted[grant.Name] = grant.SchemaDigest + } + set := &Toolset{client: s.callClient(b.HTTP), endpoint: endpoint, headers: rule.Headers, + timeout: b.Binding.Timeout, targets: map[string]target{}} + for _, tool := range rule.HTTPTools { + // A tool not granted pins no digest, which no digest matches. + want := granted[tool.Name] + digest, err := ToolSchemaDigest(tool) + if err != nil || digest != want { + continue + } + schema := inputSchema(tool) + validator, err := compileSchema(schema) + if err != nil { + continue + } + name := alias + Separator + tool.Name + set.targets[name] = target{tool: tool, validator: validator} + set.tools = append(set.tools, offered(name, tool.Description, schema)) + } + return set, nil +} + +// ToolSchemaDigest is the SHA-256, in hex, of the JSON of a tool's name, description and input +// schema, which the model is shown, and of its method, path and read_only, which decide what a +// call does. A later revision that turns a POST into a read-only GET has another digest, so a +// grant pinned to one never opens the other (AI-3674): a connection pinned to the POST's +// revision is never offered the tool under a grant made for the GET, nor the reverse. +func ToolSchemaDigest(tool core.HTTPTool) (string, error) { + data, err := json.Marshal(struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema map[string]any `json:"input_schema"` + Method string `json:"method"` + Path string `json:"path"` + ReadOnly bool `json:"read_only"` + }{Name: tool.Name, Description: tool.Description, InputSchema: inputSchema(tool), + Method: tool.Method, Path: tool.Path, ReadOnly: tool.ReadOnly}) + if err != nil { + return "", stack.Wrap(fmt.Errorf("http: tool %q schema: %w", tool.Name, err)) + } + digest := sha256.Sum256(data) + return hex.EncodeToString(digest[:]), nil +} + +// callClient is the connection's client for an opened Toolset: the same client, with a timeout +// no shorter than callTimeout, so it never cuts a call before the caller's deadline. +func (s *Source) callClient(client *http.Client) *http.Client { + copied := *client + if copied.Timeout < s.callTimeout { + copied.Timeout = s.callTimeout + } + return &copied +} + +// httpSource is the manifest's http source and the URL of its endpoint. +func httpSource(b core.ResolvedBinding) (*core.SourceRule, string, error) { + rule := core.HTTPSource(b.Manifest.Sources) + if rule == nil { + return nil, "", stack.Wrap(fmt.Errorf("http: connector %q has no http source", b.Manifest.ConnectorID)) + } + endpoint := b.Manifest.Endpoints[rule.Endpoint] + if endpoint == "" { + return nil, "", stack.Wrap(fmt.Errorf("http: connector %q has no %s endpoint resolved", b.Manifest.ConnectorID, rule.Endpoint)) + } + return rule, endpoint, nil +} + +// inputSchema is the JSON Schema of a tool's arguments: an object with one property per +// parameter, of its type and with its description, and the required ones listed in name order. +// It is built of JSON's own shapes (map[string]any, []any), as jsonschema compiles it. +func inputSchema(tool core.HTTPTool) map[string]any { + properties := make(map[string]any, len(tool.Parameters)) + var required []any + for _, name := range slices.Sorted(maps.Keys(tool.Parameters)) { + parameter := tool.Parameters[name] + property := map[string]any{"type": parameter.Type} + if parameter.Description != "" { + property["description"] = parameter.Description + } + properties[name] = property + if parameter.Required { + required = append(required, name) + } + } + schema := map[string]any{"type": "object", "properties": properties} + if len(required) > 0 { + schema["required"] = required + } + return schema +} + +// compileSchema compiles a tool's input schema as draft 2020-12, the draft the mcp source +// compiles under (mcp.compileSchema), set here rather than left to jsonschema/v6's newest. +func compileSchema(schema map[string]any) (*jsonschema.Schema, error) { + compiler := jsonschema.NewCompiler() + compiler.DefaultDraft(jsonschema.Draft2020) + if err := compiler.AddResource(schemaLocation, schema); err != nil { + return nil, err + } + return compiler.Compile(schemaLocation) +} diff --git a/acceleration/internal/connectors/sources/http/source_test.go b/acceleration/internal/connectors/sources/http/source_test.go new file mode 100644 index 0000000000..a0a579696c --- /dev/null +++ b/acceleration/internal/connectors/sources/http/source_test.go @@ -0,0 +1,706 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core/contracttest" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/bearer" + "github.com/GetStream/Vision-Agents/acceleration/internal/egress" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" +) + +// requestTimeout bounds every request a test's client sends, so a broken source fails the test +// instead of hanging it. A choice: loopback answers in milliseconds. +const requestTimeout = 5 * time.Second + +// shortTimeout is a timeout a test waits out on purpose: long enough for nothing on loopback, +// short against slowFor. A choice. +const shortTimeout = 100 * time.Millisecond + +// slowFor is how long the provider's /slow takes to answer, past shortTimeout. A choice. +const slowFor = 300 * time.Millisecond + +func TestHTTPSourceContract(t *testing.T) { + suite.Run(t, &contracttest.SourceContract{New: func(t *testing.T) contracttest.SourceSubject { + p := newProvider(t) + binding := p.binding(t, requestTimeout, contractTools()...) + return contracttest.SourceSubject{ + Source: New(), + Binding: binding, + Calls: p.calls, + // The manifest is the provider's list, so a changed schema is a changed manifest. + ChangeSchema: func() { + binding.Manifest.Sources[0].HTTPTools[0].Parameters["loud"] = core.HTTPParameter{Type: "boolean"} + }, + } + }}) +} + +// SourceSuite is what the http source does beyond the contract, against an API behind a TLS +// server on loopback that takes one bearer token, reached through core.Transports with the +// bearer scheme. +type SourceSuite struct { + suite.Suite + ctx context.Context + provider *provider + source *Source +} + +func TestSourceSuite(t *testing.T) { + suite.Run(t, new(SourceSuite)) +} + +func (s *SourceSuite) SetupTest() { + s.ctx = context.Background() + s.provider = newProvider(s.T()) + s.source = New() +} + +// AC of AI-3674: a GET sends its {name} in the path, escaped as one segment, and its other +// parameters in the query, each as the model wrote it; one left out is not sent. The manifest's +// headers and the connection's credential are on it. +func (s *SourceSuite) TestAGETSendsItsPathParameterInThePathAndTheOthersInTheQuery() { + tool := core.HTTPTool{Name: "get_forecast", Method: http.MethodGet, Path: "/v1/forecast/{city}", ReadOnly: true, + Parameters: map[string]core.HTTPParameter{ + "city": {Type: "string", Required: true}, "latitude": {Type: "number", Required: true}, + "current": {Type: "string"}, "days": {Type: "integer"}, "past": {Type: "boolean"}, "hourly": {Type: "boolean"}, + }} + + result, err := s.call(s.binding(tool), "get_forecast", + `{"city":"New York/old?x","latitude":52.520000000000000001,"current":"temperature_2m","days":7,"past":false}`) + + s.Require().NoError(err) + s.Equal("ok", llm.TextOf(result.Parts)) + sent := s.only() + s.Equal(http.MethodGet, sent.method) + s.Equal("/api/v1/forecast/New%20York%2Fold%3Fx", sent.path) + s.Equal(url.Values{"latitude": {"52.520000000000000001"}, "current": {"temperature_2m"}, "days": {"7"}, "past": {"false"}}, + sent.query, "no city, which went in the path, and no hourly, which was left out") + s.Empty(sent.body) + s.Equal("Bearer token-1", sent.header.Get("Authorization")) + s.Equal("2", sent.header.Get("X-Api-Version"), "the manifest's source header") + s.Empty(sent.header.Get("Content-Type")) +} + +// AC of AI-3674 and AC-8 of AI-3669: a POST sends its other parameters as a JSON object, numbers +// as the model wrote them, so 2^53+1 is not rounded through a float. +func (s *SourceSuite) TestAPOSTSendsItsOtherParametersAsAJSONBody() { + tool := core.HTTPTool{Name: "echo", Method: http.MethodPost, Path: "/items/{id}", + Parameters: map[string]core.HTTPParameter{ + "id": {Type: "string", Required: true}, "message": {Type: "string", Required: true}, + "count": {Type: "integer"}, "urgent": {Type: "boolean"}, + }} + + _, err := s.call(s.binding(tool), "echo", `{"id":"42","message":"hello-3669","count":9007199254740993,"urgent":true}`) + + s.Require().NoError(err) + sent := s.only() + s.Equal(http.MethodPost, sent.method) + s.Equal("/api/items/42", sent.path) + s.Empty(sent.query) + s.JSONEq(`{"message":"hello-3669","count":9007199254740993,"urgent":true}`, sent.body) + s.Contains(sent.body, "9007199254740993") + s.Equal("application/json", sent.header.Get("Content-Type")) +} + +// AI-3669 «Decided»: the query for GET, HEAD and DELETE, a JSON body for POST, PUT and PATCH, +// which is an empty object when every parameter went in the path. +func (s *SourceSuite) TestEachMethodSendsItsParametersWhereTheRuleSays() { + for _, test := range []struct { + method, arguments string + query url.Values + body string + }{ + {http.MethodGet, `{"id":"7","q":"x"}`, url.Values{"q": {"x"}}, ""}, + {http.MethodHead, `{"id":"7","q":"x"}`, url.Values{"q": {"x"}}, ""}, + {http.MethodDelete, `{"id":"7","q":"x"}`, url.Values{"q": {"x"}}, ""}, + {http.MethodPost, `{"id":"7","q":"x"}`, url.Values{}, `{"q":"x"}`}, + {http.MethodPut, `{"id":"7","q":"x"}`, url.Values{}, `{"q":"x"}`}, + {http.MethodPatch, `{"id":"7","q":"x"}`, url.Values{}, `{"q":"x"}`}, + {http.MethodPost, `{"id":"7"}`, url.Values{}, `{}`}, + } { + s.provider.reset() + tool := core.HTTPTool{Name: "act", Method: test.method, Path: "/items/{id}", + Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}, "q": {Type: "string"}}} + + _, err := s.call(s.binding(tool), "act", test.arguments) + + s.Require().NoError(err, test.method) + sent := s.only() + s.Equal(test.method, sent.method) + s.Equal("/api/items/7", sent.path, test.method) + s.Equal(test.query, sent.query, test.method) + s.Equal(test.body, sent.body, test.method) + } +} + +// Only what the tool declares is sent: an override the model adds goes nowhere (AC-6 of AI-3669, +// whose refusal before sending is AI-3675's). +func (s *SourceSuite) TestAnArgumentTheToolDoesNotDeclareIsNotSent() { + _, err := s.call(s.binding(echoTool()), contracttest.ToolEcho, + `{"text":"hi","_method":"DELETE","X-HTTP-Method-Override":"DELETE"}`) + + s.Require().NoError(err) + sent := s.only() + s.Equal(http.MethodGet, sent.method) + s.Equal(url.Values{"text": {"hi"}}, sent.query) + s.Empty(sent.header.Get("X-HTTP-Method-Override")) +} + +func (s *SourceSuite) TestNoArgumentsAtAllAreAnEmptyObject() { + tool := core.HTTPTool{Name: "list", Method: http.MethodGet, Path: "/items"} + + result, err := s.call(s.binding(tool), "list", " ") + + s.Require().NoError(err) + s.Equal("ok", llm.TextOf(result.Parts)) + s.Equal("/api/items", s.only().uri, "no query, not even an empty one") +} + +// The endpoint and the path are joined as text: the endpoint's own path stays, which resolving +// the path as a reference would drop, and a / ending the endpoint is not doubled. +func (s *SourceSuite) TestTheEndpointsOwnPathIsKeptAndItsTrailingSlashNotDoubled() { + binding := s.binding(echoTool()) + binding.Manifest.Endpoints[Kind] = s.provider.URL + "/api/" + + _, err := s.call(binding, contracttest.ToolEcho, `{"text":"hi"}`) + + s.Require().NoError(err) + s.Equal("/api/echo", s.only().path) +} + +// AC-4 of AI-3669: an answer that is not a 2xx is a tool error naming its status, with the +// API's words when it said any. +func (s *SourceSuite) TestAnAnswerThatIsNotA2xxIsAToolErrorNamingItsStatus() { + for path, want := range map[string]string{ + "/missing": "The API answered 404 Not Found: no such item", + "/multiple-choices": "The API answered 300 Multiple Choices", + "/refused": "The API answered 401 Unauthorized: bad token", + } { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: path} + + _, err := s.call(s.binding(tool), "get", `{}`) + + var reported *core.ToolError + s.Require().ErrorAs(err, &reported, path) + s.Equal(want, reported.Message, path) + } + result, err := s.call(s.binding(core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/last-2xx"}), "get", `{}`) + s.Require().NoError(err, "299 is the last 2xx") + s.Equal("ok", llm.TextOf(result.Parts)) +} + +// R1.5: a 2xx with no body, such as a DELETE's 204 or any HEAD's answer, is its status line, so +// the model can tell done from nothing. +func (s *SourceSuite) TestAnEmpty2xxIsItsStatus() { + for want, tool := range map[string]core.HTTPTool{ + "The API answered 204 No Content.": {Name: "remove", Method: http.MethodDelete, Path: "/no-content"}, + "The API answered 200 OK.": {Name: "check", Method: http.MethodHead, Path: "/items"}, + } { + result, err := s.call(s.binding(tool), tool.Name, `{}`) + + s.Require().NoError(err, tool.Method) + s.Equal(want, llm.TextOf(result.Parts), tool.Method) + } +} + +func (s *SourceSuite) TestAToolErrorOverTheCapIsCutWithTheMarker() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/error-large"} + + _, err := s.call(s.binding(tool), "get", `{}`) + + var reported *core.ToolError + s.Require().ErrorAs(err, &reported) + s.LessOrEqual(len(reported.Message), core.MaxResultBytes) + s.True(strings.HasSuffix(reported.Message, core.TruncatedMarker)) +} + +func (s *SourceSuite) TestABodyThatIsNotTextReadsAsNotText() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/binary"} + + result, err := s.call(s.binding(tool), "get", `{}`) + + s.Require().NoError(err) + s.Equal(nonText, llm.TextOf(result.Parts)) +} + +// The provider answers 4 MiB of text and then a byte that is not UTF-8: read past the cap, the +// body would be no text at all. +func (s *SourceSuite) TestABodyIsReadOnlyUpToTheCap() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/huge"} + + result, err := s.call(s.binding(tool), "get", `{}`) + + s.Require().NoError(err) + text := llm.TextOf(result.Parts) + s.True(strings.HasPrefix(text, "aaaa")) + s.True(strings.HasSuffix(text, core.TruncatedMarker)) +} + +// R1.2: valid text whose cut at the cap falls inside a rune is still text, cut before that rune. +func (s *SourceSuite) TestTextTheCapCutsInsideARuneIsStillText() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/huge-runes"} + + result, err := s.call(s.binding(tool), "get", `{}`) + + s.Require().NoError(err) + text := llm.TextOf(result.Parts) + s.True(strings.HasPrefix(text, "aaaa"), "not %q", nonText) + s.True(strings.HasSuffix(text, core.TruncatedMarker)) +} + +// R1.3: the last byte under the 4 MiB cap is read: a body whose last byte there is not UTF-8 is +// not text, under a cap even one byte lower too. +func (s *SourceSuite) TestTheLastByteUnderTheCapIsRead() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/bad-byte-at-the-cap"} + + result, err := s.call(s.binding(tool), "get", `{}`) + + s.Require().NoError(err) + s.Equal(nonText, llm.TextOf(result.Parts)) +} + +// R1.3: a 4xx or a 5xx whose body is not text names its status and says so, never the bytes. +func (s *SourceSuite) TestAToolErrorWithABodyThatIsNotTextSaysItIsNotText() { + _, err := s.call(s.binding(core.HTTPTool{Name: "broken", Method: http.MethodGet, Path: "/broken"}), "broken", `{}`) + + var reported *core.ToolError + s.Require().ErrorAs(err, &reported) + s.Equal("The API answered 500 Internal Server Error: "+nonText, reported.Message) +} + +// AI-3674, from the AI-3673 review (R1.3): revision 2 turns POST x into a read-only GET. A grant +// made for one revision's x never opens the other's, so a connection still pinned to revision 1 +// never runs the POST under a grant made for the read-only GET, nor the reverse. +func (s *SourceSuite) TestAGrantForAnotherRevisionOfAToolIsNeverOpened() { + post := core.HTTPTool{Name: "x", Method: http.MethodPost, Path: "/x"} + get := core.HTTPTool{Name: "x", Method: http.MethodGet, Path: "/x", ReadOnly: true} + revision1, revision2 := s.binding(post), s.binding(get) + granted1, granted2 := s.grants(revision1, "x"), s.grants(revision2, "x") + + for name, pair := range map[string]struct { + binding core.ResolvedBinding + grants []core.ToolGrant + }{ + "pinned to 1, granted at 2": {revision1, granted2}, + "pinned to 2, granted at 1": {revision2, granted1}, + } { + set, err := s.source.Open(s.ctx, pair.binding, pair.grants) + s.Require().NoError(err, name) + _, called := set.Call(s.ctx, llm.ToolCall{Name: "crm__x", Arguments: `{}`}) + + s.Empty(set.Tools(), name) + s.Error(called, name) + } + s.Zero(s.provider.calls("x"), "nothing reached the API") + + _, err := s.call(revision1, "x", `{}`) + s.Require().NoError(err, "the grant made at its own revision opens it") + s.Equal(http.MethodPost, s.only().method) +} + +// What decides a call is in the digest as much as what the model is shown: each change below +// is another digest, so a grant made before it no longer opens the tool. +func (s *SourceSuite) TestTheDigestCoversEveryFieldOfTheTool() { + base := func() core.HTTPTool { + return core.HTTPTool{Name: "get_forecast", Description: "The forecast.", Method: http.MethodGet, + Path: "/v1/forecast/{city}", Parameters: map[string]core.HTTPParameter{"city": {Type: "string", Required: true}, + "days": {Type: "integer", Description: "How many days."}}} + } + before, err := ToolSchemaDigest(base()) + s.Require().NoError(err) + again, err := ToolSchemaDigest(base()) + s.Require().NoError(err) + s.Equal(before, again) + + for name, change := range map[string]func(*core.HTTPTool){ + "name": func(t *core.HTTPTool) { t.Name = "get_weather" }, + "description": func(t *core.HTTPTool) { t.Description = "The weather." }, + "method": func(t *core.HTTPTool) { t.Method = http.MethodHead }, + "path": func(t *core.HTTPTool) { t.Path = "/v2/forecast/{city}" }, + "read_only": func(t *core.HTTPTool) { t.ReadOnly = true }, + "a parameter's type": func(t *core.HTTPTool) { + t.Parameters["days"] = core.HTTPParameter{Type: "number", Description: "How many days."} + }, + "a parameter required": func(t *core.HTTPTool) { + t.Parameters["days"] = core.HTTPParameter{Type: "integer", Description: "How many days.", Required: true} + }, + "a parameter's words": func(t *core.HTTPTool) { t.Parameters["days"] = core.HTTPParameter{Type: "integer"} }, + "one parameter more": func(t *core.HTTPTool) { t.Parameters["past"] = core.HTTPParameter{Type: "boolean"} }, + } { + tool := base() + change(&tool) + after, err := ToolSchemaDigest(tool) + s.Require().NoError(err, name) + s.NotEqual(before, after, name) + } +} + +// The model is shown each declared parameter with its type and its description, and the +// required ones; a tool that requires none lists no required. +func (s *SourceSuite) TestTheInputSchemaIsTheDeclaredParameters() { + forecast := core.HTTPTool{Name: "get_forecast", Description: "The forecast.", Method: http.MethodGet, + Path: "/v1/forecast/{city}", Parameters: map[string]core.HTTPParameter{ + "days": {Type: "integer", Description: "How many days."}, "city": {Type: "string", Required: true}, + "at": {Type: "number", Required: true}}} + list := core.HTTPTool{Name: "list", Method: http.MethodGet, Path: "/items", + Parameters: map[string]core.HTTPParameter{"q": {Type: "string"}}} + binding := s.binding(forecast, list) + + specs, err := s.source.Discover(s.ctx, binding) + + s.Require().NoError(err) + s.Require().Len(specs, 2) + want := map[string]any{"type": "object", "properties": map[string]any{ + "at": map[string]any{"type": "number"}, "city": map[string]any{"type": "string"}, + "days": map[string]any{"type": "integer", "description": "How many days."}, + }, "required": []any{"at", "city"}} + s.Equal("get_forecast", specs[0].Name) + s.Equal("The forecast.", specs[0].Description) + s.Equal(want, specs[0].InputSchema) + s.Equal(map[string]any{"type": "object", "properties": map[string]any{"q": map[string]any{"type": "string"}}}, + specs[1].InputSchema) + set, err := s.source.Open(s.ctx, binding, s.grants(binding, "get_forecast")) + s.Require().NoError(err) + s.Equal([]llm.Tool{{Name: "crm__get_forecast", Description: "The forecast.", Parameters: want}}, set.Tools()) + s.Empty(set.Instructions(), "an API says nothing when a session opens") +} + +func (s *SourceSuite) TestABindingNameMustBeSetAndHoldNoSeparator() { + for _, name := range []string{"", "my__crm"} { + binding := s.binding(echoTool()) + binding.Binding.Name = name + + _, err := s.source.Open(s.ctx, binding, s.grants(binding, contracttest.ToolEcho)) + + s.Error(err, name) + } +} + +func (s *SourceSuite) TestABindingWithNoClientIsRefused() { + binding := s.binding(echoTool()) + grants := s.grants(binding, contracttest.ToolEcho) + binding.HTTP = nil + + _, err := s.source.Open(s.ctx, binding, grants) + + s.ErrorContains(err, "no client") +} + +func (s *SourceSuite) TestAManifestWithNoHTTPSourceOrNoEndpointIsRefused() { + noSource := s.binding(echoTool()) + noSource.Manifest.Sources = []core.SourceRule{{Kind: core.SourceKindMCP, Endpoint: core.SourceKindMCP}} + noEndpoint := s.binding(echoTool()) + noEndpoint.Manifest.Endpoints = map[string]string{} + + for want, binding := range map[string]core.ResolvedBinding{"has no http source": noSource, "has no http endpoint": noEndpoint} { + _, err := s.source.Discover(s.ctx, binding) + s.ErrorContains(err, want) + _, err = s.source.Open(s.ctx, binding, nil) + s.ErrorContains(err, want) + } +} + +// The connection's client cuts a request at its own timeout, which validate's requests keep; an +// opened toolset's copy waits at least callTimeout, so the caller's deadline ends a call first. +func (s *SourceSuite) TestAnOpenedToolsetWaitsPastTheConnectionsClientTimeout() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/slow"} + binding := s.provider.binding(s.T(), shortTimeout, tool) + + result, err := s.call(binding, "get", `{}`) + + s.Require().NoError(err) + s.Equal("late", llm.TextOf(result.Parts)) + s.Equal(shortTimeout, binding.HTTP.Timeout, "the binding's own client is left as it was") +} + +// A client that already waits longer than callTimeout keeps its own timeout. +func (s *SourceSuite) TestAClientWaitingLongerThanCallTimeoutKeepsItsTimeout() { + for timeout, want := range map[time.Duration]time.Duration{ + shortTimeout: defaultCallTimeout, defaultCallTimeout: defaultCallTimeout, time.Minute: time.Minute, + } { + binding := s.provider.binding(s.T(), timeout, echoTool()) + + set, err := s.source.Open(s.ctx, binding, s.grants(binding, contracttest.ToolEcho)) + + s.Require().NoError(err) + s.Equal(want, set.(*Toolset).client.Timeout, timeout) + } +} + +func (s *SourceSuite) TestABodyCutShortIsAnErrorNotAnAnswer() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/cut"} + + _, err := s.call(s.binding(tool), "get", `{}`) + + s.ErrorIs(err, io.ErrUnexpectedEOF) + s.EqualError(err, unreachedSentence, "what the model reads") + s.Contains(core.LoggedMessage(err, nil), "unexpected EOF", "what the log line reads") + var reported *core.ToolError + s.False(errors.As(err, &reported), "the API never finished its answer, so it reported nothing") +} + +// S1.1 of AI-3674: a host the egress policy refuses and one that does not resolve read the same +// one sentence, with no URL, no argument and nothing of the policy or the resolver; the log line +// keeps why (core.LoggedMessage). +func (s *SourceSuite) TestACallThatReachesNoAPIReadsOneSentence() { + lookup := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/people/{id}", + Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}, "email": {Type: "string"}}} + transports, err := core.NewTransports(core.TransportsConfig{Resolver: tokenResolver{}, Timeout: requestTimeout}) + s.Require().NoError(err) + + for _, endpoint := range []string{"https://127.0.0.1:8443/api", "https://no-such-host-ai3674.invalid/api"} { + binding := s.binding(lookup) + binding.Manifest.Endpoints[Kind] = endpoint + binding.HTTP = transports.Client(core.ConnectionRef{CustomerID: "app", ConnectionID: "crm-1"}, bearer.New()) + + _, err := s.call(binding, "get", `{"id":"u1","email":"alice@example.com"}`) + + s.EqualError(err, unreachedSentence, endpoint) + s.Contains(core.LoggedMessage(err, nil), "egress", endpoint) + } +} + +// unreachedSentence is what the model reads of a call to crm__get that got no whole answer. +const unreachedSentence = "http: crm__get: the API could not be reached, or its answer did not arrive whole" + +func (s *SourceSuite) TestTheBindingsTimeoutBoundsACall() { + tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/slow"} + binding := s.binding(tool) + binding.Binding.Timeout = shortTimeout + + _, err := s.call(binding, "get", `{}`) + + s.ErrorIs(err, context.DeadlineExceeded) +} + +// call opens a toolset of the binding granting tool at its current digest and calls it. +func (s *SourceSuite) call(binding core.ResolvedBinding, tool, arguments string) (core.Result, error) { + set, err := s.source.Open(s.ctx, binding, s.grants(binding, tool)) + s.Require().NoError(err) + s.T().Cleanup(set.Close) + s.Require().Len(set.Tools(), 1, tool) + return set.Call(s.ctx, llm.ToolCall{Name: binding.Binding.Name + Separator + tool, Arguments: arguments}) +} + +// grants grants tools at the digest Discover gives them now. +func (s *SourceSuite) grants(binding core.ResolvedBinding, tools ...string) []core.ToolGrant { + specs, err := s.source.Discover(s.ctx, binding) + s.Require().NoError(err) + var grants []core.ToolGrant + for _, spec := range specs { + for _, tool := range tools { + if spec.Name == tool { + grants = append(grants, core.ToolGrant{Name: spec.Name, SchemaDigest: spec.SchemaDigest}) + } + } + } + s.Require().Len(grants, len(tools)) + return grants +} + +// only is the one request the provider received. +func (s *SourceSuite) only() sent { + received := s.provider.requests() + s.Require().Len(received, 1) + return received[0] +} + +func (s *SourceSuite) binding(tools ...core.HTTPTool) core.ResolvedBinding { + return s.provider.binding(s.T(), requestTimeout, tools...) +} + +func echoTool() core.HTTPTool { + return core.HTTPTool{Name: contracttest.ToolEcho, Description: "Returns the text it is given.", Method: http.MethodGet, + Path: "/echo", Parameters: map[string]core.HTTPParameter{"text": {Type: "string", Required: true}}} +} + +// contractTools are the three tools contracttest.SourceContract calls. +func contractTools() []core.HTTPTool { + return []core.HTTPTool{ + echoTool(), + {Name: contracttest.ToolLarge, Description: "Answers at length.", Method: http.MethodGet, Path: "/large"}, + {Name: contracttest.ToolBroken, Description: "Fails with a picture.", Method: http.MethodGet, Path: "/broken"}, + } +} + +// sent is one request as the provider received it. +type sent struct { + method string + // uri is the request line's target, and path its path as it was sent, escaped. + uri string + path string + query url.Values + body string + header http.Header +} + +// provider is an API behind a TLS server that takes only the bearer token token-1, records each +// request and answers by path. +type provider struct { + *httptest.Server + mu sync.Mutex + received []sent +} + +func newProvider(t *testing.T) *provider { + p := &provider{} + p.Server = httptest.NewTLSServer(http.HandlerFunc(p.serve)) + t.Cleanup(p.Close) + return p +} + +func (p *provider) serve(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + p.mu.Lock() + p.received = append(p.received, sent{method: r.Method, uri: r.RequestURI, path: r.URL.EscapedPath(), query: r.URL.Query(), + body: string(body), header: r.Header.Clone()}) + p.mu.Unlock() + if r.Header.Get("Authorization") != "Bearer token-1" { + w.WriteHeader(http.StatusUnauthorized) + return + } + switch strings.TrimPrefix(r.URL.Path, "/api") { + case "/echo": + _, _ = io.WriteString(w, r.URL.Query().Get("text")) + case "/large": + // Two bytes per character, so the cut can land inside one. + _, _ = io.WriteString(w, strings.Repeat("é", core.MaxResultBytes)) + case "/broken": + w.Header().Set("Content-Type", "image/png") + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte{0x89, 'P', 'N', 'G', 0xff, 0xfe}) + case "/binary": + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write([]byte{0x89, 'P', 'N', 'G', 0xff, 0xfe}) + case "/huge": + // 4 MiB, the cap AI-3669 decided, written out so a changed maxResponseBytes fails the test. + _, _ = io.WriteString(w, strings.Repeat("a", 4<<20)) + _, _ = w.Write([]byte{0xff}) + case "/huge-runes": + // The cut at 4 MiB falls inside the first é. + _, _ = io.WriteString(w, strings.Repeat("a", 4<<20-1)+"éééé") + case "/bad-byte-at-the-cap": + _, _ = io.WriteString(w, strings.Repeat("a", 4<<20-1)) + _, _ = w.Write([]byte{0xff}) + case "/no-content": + w.WriteHeader(http.StatusNoContent) + case "/missing": + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, "no such item") + case "/multiple-choices": + w.WriteHeader(http.StatusMultipleChoices) + case "/last-2xx": + w.WriteHeader(299) + _, _ = io.WriteString(w, "ok") + case "/cut": + // Fewer bytes than the length it says: the server then closes the connection. + w.Header().Set("Content-Length", "100") + _, _ = io.WriteString(w, "only ten b") + case "/refused": + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, "bad token") + case "/error-large": + w.WriteHeader(http.StatusInternalServerError) + _, _ = io.WriteString(w, strings.Repeat("x", 2*core.MaxResultBytes)) + case "/slow": + select { + case <-time.After(slowFor): + _, _ = io.WriteString(w, "late") + case <-r.Context().Done(): + } + default: + _, _ = io.WriteString(w, "ok") + } +} + +// binding reaches the provider's /api under the alias crm, through core.Transports with the +// bearer scheme and a client that cuts a request at timeout, with tools as its http source's. +func (p *provider) binding(t *testing.T, timeout time.Duration, tools ...core.HTTPTool) core.ResolvedBinding { + transports, err := core.NewTransports(core.TransportsConfig{Resolver: tokenResolver{}, Timeout: timeout, NewClient: loopback(p.Client())}) + if err != nil { + t.Fatal(err) + } + return core.ResolvedBinding{ + Binding: core.Binding{Name: "crm"}, + Manifest: core.ResolvedManifest{ + ConnectorID: "custom_crm", + Scheme: bearer.Name, + Endpoints: map[string]string{Kind: p.URL + "/api"}, + Sources: []core.SourceRule{{Kind: Kind, Endpoint: Kind, HTTPTools: tools, + Headers: map[string]string{"X-Api-Version": "2"}}}, + }, + HTTP: transports.Client(core.ConnectionRef{CustomerID: "app", ConnectionID: "crm-1"}, bearer.New()), + } +} + +// calls is how many requests reached the provider for the tool at /api/. +func (p *provider) calls(tool string) int { + p.mu.Lock() + defer p.mu.Unlock() + count := 0 + for _, request := range p.received { + if request.path == "/api/"+tool { + count++ + } + } + return count +} + +// requests are the requests the provider received, in order. +func (p *provider) requests() []sent { + p.mu.Lock() + defer p.mu.Unlock() + return append([]sent{}, p.received...) +} + +func (p *provider) reset() { + p.mu.Lock() + defer p.mu.Unlock() + p.received = nil +} + +// loopback is egress.NewClient for a test: the same redirect policy, but the TLS server's +// transport, because egress refuses loopback, where httptest listens. +func loopback(server *http.Client) core.NewClientFunc { + policy := egress.NewClient(0, nil).CheckRedirect + return func(timeout time.Duration, wrap func(http.RoundTripper) http.RoundTripper) *http.Client { + return &http.Client{Transport: wrap(server.Transport), Timeout: timeout, CheckRedirect: policy} + } +} + +// tokenResolver hands out the bearer token token-1 for every connection. +type tokenResolver struct{} + +func (tokenResolver) Resolve(context.Context, core.ConnectionRef, core.CredentialRequest) (core.AccessCredential, error) { + secret, err := json.Marshal(map[string]string{"token": "token-1"}) + if err != nil { + return core.AccessCredential{}, err + } + credential := core.NewAccessCredential(bearer.Name, time.Time{}, secret) + credential.Revision = 1 + return credential, nil +} + +// Invalidate is told of a 401 nothing renews, as the store's resolver is, and the 401 is then +// the call's answer (core.Transports). +func (tokenResolver) Invalidate(context.Context, core.ConnectionRef, core.AccessCredential, core.Outcome) error { + return nil +} + +func (tokenResolver) Revoke(context.Context, core.ConnectionRef, core.SignalKind, time.Time) error { + return nil +} diff --git a/acceleration/internal/connectors/sources/http/toolset.go b/acceleration/internal/connectors/sources/http/toolset.go new file mode 100644 index 0000000000..c7fba56c78 --- /dev/null +++ b/acceleration/internal/connectors/sources/http/toolset.go @@ -0,0 +1,201 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "maps" + "net/http" + "net/url" + "regexp" + "slices" + "strings" + "time" + "unicode/utf8" + + "github.com/santhosh-tekuri/jsonschema/v6" + + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" +) + +// maxResponseBytes is the most of one response body a call reads: the mcp source's cap +// (mcp.maxResponseBytes, 4 MiB), which AI-3669 reuses («MCP's size caps are reused»), so an API +// that answers without end cannot exhaust the router's memory. The model reads at most +// core.MaxResultBytes of it. A call reads one byte past it, to tell a body the cap cut from one +// that ends at the cap. +const maxResponseBytes = 4 << 20 + +// nonText is what the model reads for a body that is not UTF-8 text, such as an image: the mcp +// source's wording for content that is not text (mcp.nonText). +const nonText = "The tool returned content that is not text, which the agent cannot read" + +// placeholder is a {name} in a tool's path, as core.Manifest.Validate reads one (placeholder in +// core/manifest.go). +var placeholder = regexp.MustCompile(`\{([^{}]*)\}`) + +// bodyMethods are the methods whose parameters go in a JSON body (AI-3669, «Decided»); those of +// GET, HEAD and DELETE go in the query. +var bodyMethods = []string{http.MethodPost, http.MethodPut, http.MethodPatch} + +// Toolset is the granted tools of one http source, opened for one session. It is safe for +// concurrent use: its tools are fixed when Open returns, and each call is its own request. +type Toolset struct { + client *http.Client + // endpoint is the source's base URL, which each tool's path is appended to. + endpoint string + // headers are the manifest's sources[].headers, set on every request. + headers map[string]string + // timeout bounds one call; zero leaves it to the caller's context. + timeout time.Duration + tools []llm.Tool + // targets are the offered tools by the name the model calls them. + targets map[string]target +} + +var _ core.Toolset = (*Toolset)(nil) + +// target is one offered tool: its definition and its input schema. +type target struct { + tool core.HTTPTool + validator *jsonschema.Schema +} + +// Tools are the tools the model is offered. +func (t *Toolset) Tools() []llm.Tool { + return t.tools +} + +// Instructions is empty: an API says nothing about its tools when a session opens. +func (*Toolset) Instructions() string { + return "" +} + +// Call runs one offered tool: one request, whose answer the model reads as text. A name this +// toolset did not offer, or arguments its input schema refuses, never reach the API. An answer +// that is not a 2xx is a *core.ToolError naming its status, and an empty 2xx is its status. A +// result past core.MaxResultBytes is cut and ends with core.TruncatedMarker. +func (t *Toolset) Call(ctx context.Context, call llm.ToolCall) (core.Result, error) { + offered, found := t.targets[call.Name] + if !found { + return core.Result{}, stack.Wrap(fmt.Errorf("http: %q is not a tool this connection offers", call.Name)) + } + raw := strings.TrimSpace(call.Arguments) + if raw == "" { + raw = "{}" + } + // Numbers stay json.Number, so one goes into a query or a body as the model wrote it. + arguments, err := jsonschema.UnmarshalJSON(strings.NewReader(raw)) + if err != nil { + return core.Result{}, stack.Wrap(fmt.Errorf("http: %s: the arguments are not JSON: %w", call.Name, err)) + } + if err := offered.validator.Validate(arguments); err != nil { + return core.Result{}, stack.Wrap(fmt.Errorf("http: %s: the arguments do not match the tool's input schema", call.Name)) + } + if t.timeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, t.timeout) + defer cancel() + } + // The schema takes only an object, so arguments is one. + request, err := t.request(ctx, offered.tool, arguments.(map[string]any)) + if err != nil { + return core.Result{}, err + } + response, err := t.client.Do(request) + if err != nil { + return core.Result{}, stack.Wrap(unreached(call.Name, err)) + } + defer func() { _ = response.Body.Close() }() + read, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBytes+1)) + if err != nil { + return core.Result{}, stack.Wrap(unreached(call.Name, fmt.Errorf("read the answer: %w", err))) + } + // A body past the cap is cut at it, back to the start of the rune the cut falls in, so text + // cut inside a rune is still text. + body := core.CutAtRune(string(read), maxResponseBytes) + text := nonText + if utf8.ValidString(body) { + text = body + } + if response.StatusCode < 200 || response.StatusCode > 299 { + message := fmt.Sprintf("The API answered %s", response.Status) + if len(body) > 0 { + message += ": " + text + } + return core.Result{}, stack.Wrap(&core.ToolError{Message: core.CutResult(message)}) + } + // An empty answer, such as a 204's or any HEAD's, is its status, so the model can tell a + // call that was done from one that said nothing. + if len(body) == 0 { + return core.Result{Parts: llm.TextParts(fmt.Sprintf("The API answered %s.", response.Status))}, nil + } + return core.Result{Parts: llm.TextParts(core.CutResult(text))}, nil +} + +// unreached is a call to name that got no whole answer, for cause: one sentence for every such +// failure, so the model reads no URL, no argument and nothing of the egress policy +// (core.UnreachedError). +func unreached(name string, cause error) error { + return &core.UnreachedError{Message: fmt.Sprintf("http: %s: the API could not be reached, or its answer did not arrive whole", name), Err: cause} +} + +// Close does nothing: the connection's client and its pool are core.Transports'. +func (*Toolset) Close() {} + +// request is the tool's request with arguments (AI-3669, «Decided»): each {name} in the path is +// its argument, escaped as one segment; the other parameters go in the query of a GET, a HEAD or +// a DELETE, and in a JSON object, the body, of a POST, a PUT or a PATCH. Only the parameters the +// tool declares are sent. The URL is the endpoint and the path joined as text, never resolved as +// a reference, which would drop the endpoint's own path. +func (t *Toolset) request(ctx context.Context, tool core.HTTPTool, arguments map[string]any) (*http.Request, error) { + inPath := map[string]bool{} + path := placeholder.ReplaceAllStringFunc(tool.Path, func(match string) string { + name := match[1 : len(match)-1] + inPath[name] = true + return url.PathEscape(fmt.Sprint(arguments[name])) + }) + query := url.Values{} + fields := map[string]any{} + for _, name := range slices.Sorted(maps.Keys(tool.Parameters)) { + value, given := arguments[name] + switch { + case !given || inPath[name]: + case slices.Contains(bodyMethods, tool.Method): + fields[name] = value + default: + query.Set(name, fmt.Sprint(value)) + } + } + target := strings.TrimSuffix(t.endpoint, "/") + path + if len(query) > 0 { + target += "?" + query.Encode() + } + var body io.Reader + if slices.Contains(bodyMethods, tool.Method) { + encoded, err := json.Marshal(fields) + if err != nil { + return nil, stack.Wrap(fmt.Errorf("http: %s: encode the body: %w", tool.Name, err)) + } + body = bytes.NewReader(encoded) + } + request, err := http.NewRequestWithContext(ctx, tool.Method, target, body) + if err != nil { + return nil, stack.Wrap(fmt.Errorf("http: %s: build the request: %w", tool.Name, err)) + } + for name, value := range t.headers { + request.Header.Set(name, value) + } + if body != nil { + request.Header.Set("Content-Type", "application/json") + } + return request, nil +} + +// offered is a tool as the model is shown it. +func offered(name, description string, schema map[string]any) llm.Tool { + return llm.Tool{Name: name, Description: description, Parameters: schema} +} diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 3506081499..70f6640c19 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -1657,6 +1657,12 @@ func importableDefinition(row json.RawMessage) (json.RawMessage, error) { if err != nil { return nil, fmt.Errorf("store: imported connector definition %q: %w: %w", id, ErrNotACustomConnector, err) } + // The http source runs a stored tool before the call-time checks of AI-3675 exist, and the + // API stores no http connector before AI-3676, so no import stores one either, even one the + // rules above let through. AI-3676 lifts this. + if core.HTTPSource(custom.Sources) != nil { + return nil, fmt.Errorf("store: imported connector definition %q: %w: an http connector cannot be imported yet", id, ErrNotACustomConnector) + } if fields["manifest"], err = json.Marshal(custom); err != nil { return nil, stack.Wrap(err) } diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index fd1dab7d50..65606c4989 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -2422,14 +2422,14 @@ const customWeather = `{"id": "custom_acme", "revision": 1, "name": "Weather", " "schemes": ["api_key"], "sources": [{"kind": "http", "endpoint": "http", "http_tools": [{"name": "get_forecast", "method": "GET", "path": "/forecast/{city}", "read_only": true, "parameters": {"city": {"type": "string", "required": true}}}]}]}` -func (s *DataMoveSuite) TestAnImportedHTTPDefinitionArrivesAsItWasSent() { +// TestAnImportedHTTPDefinitionIsRefused: a definition the API would store for an http connector +// is refused, and writes nothing, until AI-3676 lifts it (importableDefinition). +func (s *DataMoveSuite) TestAnImportedHTTPDefinitionIsRefused() { id, err := s.importDefinition(customWeather) - s.Require().NoError(err) - var stored string - s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, - "SELECT manifest FROM connector_definitions WHERE customer_id = 'moved' AND id = ?", id).Scan(&stored)) - s.JSONEq(strings.Replace(customWeather, "custom_acme", id, 1), stored) + s.ErrorIs(err, ErrNotACustomConnector) + s.ErrorContains(err, "an http connector cannot be imported yet") + s.Zero(s.definitionsNamed(id)) } // TestAnImportedHTTPDefinitionWhoseReadOnlyToolWritesIsRefused: the http tool rules diff --git a/acceleration/internal/store/datamove_unit_test.go b/acceleration/internal/store/datamove_unit_test.go new file mode 100644 index 0000000000..cf65a4ebb1 --- /dev/null +++ b/acceleration/internal/store/datamove_unit_test.go @@ -0,0 +1,41 @@ +package store + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/suite" +) + +// ImportableDefinitionSuite is which imported connector definitions an import would store +// (importableDefinition), without a database. +type ImportableDefinitionSuite struct { + suite.Suite +} + +func TestImportableDefinitionSuite(t *testing.T) { + suite.Run(t, new(ImportableDefinitionSuite)) +} + +// AI-3674 R1.1: the http source would run an imported http connector's tools before AI-3675's +// call-time checks, so an import refuses one until AI-3676 lifts it. An MCP one is still stored. +func (s *ImportableDefinitionSuite) TestAnHTTPConnectorIsRefusedAndAnMCPOneKept() { + http := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"http": "https://api.crm.example"}, + "schemes": ["bearer"], "sources": [{"kind": "http", "endpoint": "http", + "http_tools": [{"name": "delete_item", "method": "DELETE", "path": "/items/{id}", + "parameters": {"id": {"type": "string", "required": true}}}]}]}` + mcp := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"mcp": "https://mcp.crm.example/mcp"}, + "schemes": ["bearer"], "sources": [{"kind": "mcp", "endpoint": "mcp"}]}` + + _, err := importableDefinition(json.RawMessage(`{"id": "custom_crm", "manifest": ` + http + `}`)) + + s.ErrorIs(err, ErrNotACustomConnector) + s.ErrorContains(err, "an http connector cannot be imported yet") + + row, err := importableDefinition(json.RawMessage(`{"id": "custom_crm", "manifest": ` + mcp + `}`)) + + s.Require().NoError(err) + var kept map[string]json.RawMessage + s.Require().NoError(json.Unmarshal(row, &kept)) + s.JSONEq(mcp, string(kept["manifest"])) +} From 5a798ad5de0ec04f82efe87ed7d948e74d3743c4 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 08:50:30 +0100 Subject: [PATCH 03/13] [AI-3675] HTTP connectors: call-time safety for http tools (#2324) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Leaf 3 of AI-3669 (router: run HTTP connectors). Targets `feature/ai-3669-http-connectors`, not `main`. No API change; that is leaf 4 (AI-3676). ## Why Values the model picks go into the URL and the body of an http tool's request (`sources/http`, #2316). Before leaf 4 lets anyone store an http connector, these cases must be impossible: a write through a read_only tool, a method override, a path that names another resource, a credential echoed into the conversation, and a write resent by a redirect. The checklist comes from the AI-3673 and AI-3674 reviews: Q1 stale pin, R1.6, S1.2, S1.3 and R2.1. ## How it works ``` Toolset.Call(call) sources/http/toolset.go ├─ an argument the tool does not declare -> refused, nothing sent (AC-6) ├─ arguments vs input schema -> refused, nothing sent ├─ path built segment by segment (builtPath) │ a segment with a {name} that is "", "." or ".." -> refused (S1.3) │ "../admin" -> "..%2Fadmin" "..%2F" -> "..%252F" (one segment) ├─ send through binding.HTTP (credential + egress) │ redirect: GET/HEAD follow (same origin, egress policy) │ POST/PUT/PATCH/DELETE -> the 3xx is the answer (R1.6) ├─ write's 301/302/303 -> result "The API answered 303 See Other; the request may have run." ├─ non-2xx -> ToolError "The API answered : " │ body -> Exchange.Redact (credential, path, query) -> cut 32 KiB └─ 2xx -> body -> Exchange.RedactCredential (credential values only) -> cut 32 KiB = code + http.StatusText, never the API's reason phrase Source.Open sources/http/source.go └─ core.CheckHTTPSource(rule): Validate's http rules again (override names, read_only only on GET/HEAD, a description, ...) -> error, nothing offered ``` Stale pin (AI-3674 Q1). A session opens an http tool only at the digest its grant pins, and the digest covers method, path and read_only. So `internal/api` now judges an http tool read-only only when the grant pins the latest revision's read-only digest (`grantSendsOut`): ``` revision 1: x = POST /x revision 2: x = GET /x, read_only fixed connection stays on revision 1, lists x at digest D1 before after GET .../connections/{id}/tools x read_only: true false config beside nessy, x@D1 201 (POST runs) 400 "api" x config beside nessy, x by name 201 400 config beside nessy, x@D2 201 201 (rev 1 never opens D2) ``` An MCP tool stays judged on the latest revision's `read_only_tools`. `TestReadOnlyIsTheConnectorsLatestRevisionsAsAConfigSaveChecks` pins that, and it is unchanged. ## Changes - `sources/http`: refuse undeclared arguments; judge the built path; follow redirects only for GET and HEAD (with net/http's limit of 10 when a client has no policy); redact tool errors with the call's Exchange (`core.Observed`: the dispatcher's, or one of the call's own); recheck the source at `Open`. - `core`: `CheckHTTPSource` (the http rules of `Validate`, exported for `Open`) and `Observed`. - `core`: `Exchange.RedactCredential`, the credential's secret values alone, for a 2xx answer. A scheme whose secret also holds a name says which strings are values (`core.SecretValuer`; api_key: the key, not its header name). Redaction takes the longest string out first, so a key that holds its header name goes out whole. - `core`: an http tool with no description is refused by `Validate` and at `Open`: a session refuses such a tool (`harness.Tools.Validate`), so the sync says so first. - `api`: `grantSendsOut` in `bindingSendsOut` (config check) and in `listConnectionTools` (the same class). - `fakeprovider`: an HTTP API at `/rest` (api_key header, `/bytes/?then=`, `/echo-credential` with `?status=200`, request log), for AC-6 and AC-9. - Docs: `sources/http/AGENTS.md`, `core/AGENTS.md`, `fakeprovider/AGENTS.md`, `.claude/skills/connectors/SKILL.md`. Decisions: | Case | Decision | Reason | | --- | --- | --- | | empty path value (`DELETE /items/`) | refused | it names the collection | | `{a}{b}` = `.` + `.` | refused | it is judged as built, so it is `..` | | `../admin` | sent as `..%2Fadmin` | AC-6 of AI-3669 | | `..%2F` | sent as `..%252F` | the `%` is escaped, so it is no dot segment | | 307/308 on a POST, PUT or PATCH | not followed, the 3xx is the answer | net/http would resend the body to a path the manifest does not name | | 3xx on a DELETE | not followed | a write's path is the manifest's | | 301/302/303 on a POST, PUT, PATCH or DELETE | a result: "The API answered ; the request may have run." | only a 307 or 308 asks for the request again; after the others the write may have run, so the model must not read a failure and retry (R1.2) | | status the model reads | code + `http.StatusText` | the API's reason phrase is its own text and may echo the credential (S1.1) | | http tool with no description | refused at validation | a session refuses it anyway (Q0.3) | | GET/HEAD redirect | followed, same origin only | the egress policy, unchanged | | 2xx body | the credential's secret values redacted; path, query and api_key's header name kept | an API that echoes the key in a 200 must not put it in the conversation; an answer names its resource by its path (Q1) and may name its own header (R1.1) | | `/` in a path value (`../admin`) | stays escaped as one segment (`..%2Fadmin`) | AC-6 of AI-3669; an API that decodes `%2F` before routing is out of the router's control, and the docs leaf says so (Q2) | | stale pin | an http tool reads only when the grant pins the latest revision's read-only digest | side effect, accepted as fail-closed: an http read-only tool granted by name beside a sensitive connector is refused; the docs leaf says so (Q3) | ## Validation | Rule | Test | Mutations killed | | --- | --- | --- | | undeclared argument refused | `TestSourceSuite/TestAnArgumentTheToolDoesNotDeclareIsRefusedBeforeSending` (7 shapes x GET/POST), `TestAcceptanceSuite/TestAnOverrideIsRefusedBeforeSendingAndAValidCallIsOneGET` (AC-6) | T1, T2 | | built path | `TestSourceSuite/TestAPathValueThatNamesAnotherResourceIsRefusedBeforeSending` (18 rows) | T3, T6-T12 | | Open recheck | `TestSourceSuite/TestOpenRefusesASourceThatBreaksARuleOfValidation` | S1, C1 | | redirects | `TestSourceSuite/TestOnlyAReadFollowsARedirect` (a write's 301/302/303 is a result, a read's 302 with no Location stays an error), `TestARedirectToAnotherOriginNeverCarriesTheCredential`, `TestAClientWithNoRedirectPolicyStopsAfterTenRedirects` | S2-S9; R1.2: rule off, rule for reads too, 307 added, 302 dropped | | status text | `TestSourceSuite/TestAnEmpty2xxIsItsStatus` (reason phrase echoing the token), `TestAnAnswerThatIsNotA2xxIsAToolErrorNamingItsStatus` (own phrase, unknown code) | each `response.Status` put back | | description required | `TestHTTPSourceSuite/TestAnHTTPSourceBreakingARuleIsRefused` row "no description" | check off | | key holding its header name | `TestLoggedDescriptionSuite/TestASecretHoldingAnotherIsTakenOutWhole` | sort removed | | header name kept in a 2xx | `TestAcceptanceSuite/TestA2xxKeepsTheKeysHeaderName` (a 403 still redacts it) | transport back to every string, api_key values with the header, api_key values nil, `SecretValuer` ignored | | redaction | `TestSourceSuite/TestAToolErrorEchoingTheCredentialIsRedacted` (also a token the 32 KiB cut falls in), `TestAToolErrorIsRedactedWithNoExchangeOfTheCallers`, `TestAcceptanceSuite/TestA403EchoingTheKeyIsRedacted` | T4, T5, C2, C3 | | logs | `TestAcceptanceSuite/TestALogLineHoldsNoArgumentAndNoCredential` | (KeepHosts is the base's) | | AC-9 | `TestAcceptanceSuite/TestAnAnswerIsReadUpTo4MiBAndReadAsAtMost32KiB` | F5 | | stale pin | `TestConfigsSuite/TestAnHTTPToolReadsOnlyAtTheDigestItsGrantPins`. It fails with `grantSendsOut` reverted: listing true, config 201 | A1-A7 | | stale pin, in a session | `TestSessionConnectorsSuite/TestAStalePinNeverRunsAWriteAsARead`: a fixed connection on revision 1 (echo POST); beside nessy, echo at revision 1's digest is refused, at revision 2's (read-only GET) accepted and the session leaves crm out, nothing reaches the API; without nessy the session runs the POST | grantSendsOut reverted (config 201), Source.Open digest pin reverted (crm offered) | | 2xx redaction | `TestSourceSuite/TestA2xxEchoingTheCredentialIsRedactedAndKeepsItsPath` (bearer, Authorization), `TestAcceptanceSuite/TestA200EchoingTheKeyIsRedacted` (api_key header) | no RedactCredential, Redact in its place (path lost), identity redaction, no secret | | R2.1 | `TestLoggedMessageSuite/TestAnUnreachedErrorWithNoCauseIsItsMessage` | C4 | | fake API | `TestFakeProviderSuite/TestTheHTTPAPITakesItsKeyRecordsEachRequestAndAnswersByPath` | F1-F6 | The mutation script applies, tests and restores each of 38 mutants. All 38 were killed. The author's notes keep the list. Round 1 fixes (Q0.3, S1.1, S1.2, R1.1, R1.2) ran: `go vet` with and without the `integration` tag; unit `./internal/connectors/... ./internal/api ./internal/session ./internal/store ./internal/harness ./cmd/router`; `-race` on `sources/http`, `core`, `schemes`; integration `TestConfigsSuite|TestConnectionToolsSuite|TestSessionConnectorsSuite|TestSessionToolsSuite` in `./internal/api` (455 passed) and `TestDataMoveSuite` in `./internal/store`. The author ran: - `go test ./internal/connectors/... ./cmd/router ./internal/api ./internal/session` (unit) - `go test -race ./internal/connectors/sources/http ./internal/connectors/fakeprovider` - `go test -tags integration -run 'TestConfigsSuite|TestConnectionToolsSuite|TestSyncSuite|TestSessionConnectorsSuite|TestSessionToolsSuite' ./internal/api` on its own database (539 tests) - `go vet` with and without the `integration` tag All passed. The full integration run is not done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .claude/skills/connectors/SKILL.md | 5 +- acceleration/internal/api/configs.go | 29 +- acceleration/internal/api/configs_test.go | 62 +++ acceleration/internal/api/connection_tools.go | 6 +- .../internal/api/session_connectors_test.go | 89 ++++- .../internal/connectors/core/AGENTS.md | 4 +- .../internal/connectors/core/error_body.go | 27 +- .../internal/connectors/core/http_tools.go | 23 ++ .../connectors/core/http_tools_test.go | 10 +- .../connectors/core/provider_text_test.go | 14 + .../internal/connectors/core/records.go | 36 +- .../internal/connectors/core/scheme.go | 10 + .../internal/connectors/core/transport.go | 5 +- .../connectors/fakeprovider/AGENTS.md | 1 + .../internal/connectors/fakeprovider/api.go | 79 ++++ .../connectors/fakeprovider/fakeprovider.go | 6 + .../fakeprovider/fakeprovider_test.go | 46 +++ .../connectors/schemes/apikey/scheme.go | 11 + .../connectors/sources/http/AGENTS.md | 29 +- .../sources/http/acceptance_test.go | 236 ++++++++++++ .../connectors/sources/http/source.go | 40 +- .../connectors/sources/http/source_test.go | 359 ++++++++++++++++-- .../connectors/sources/http/toolset.go | 106 +++++- acceleration/internal/store/datamove_test.go | 2 +- .../internal/store/datamove_unit_test.go | 2 +- 25 files changed, 1162 insertions(+), 75 deletions(-) create mode 100644 acceleration/internal/connectors/fakeprovider/api.go create mode 100644 acceleration/internal/connectors/sources/http/acceptance_test.go diff --git a/.claude/skills/connectors/SKILL.md b/.claude/skills/connectors/SKILL.md index a62b54a9cc..f86b2b622e 100644 --- a/.claude/skills/connectors/SKILL.md +++ b/.claude/skills/connectors/SKILL.md @@ -179,8 +179,9 @@ no round to say why, so the reply ends with a line that the approval expired, th waiting did not run (an earlier call of the reply may have), and that the person can ask again, and the step says "Not allowed in time" (`ExpireApprovals`, `conversation/parts.go`, AI-3302). An entry must match a tool the binding grants, and `sandbox: true` is refused beside it (`session/connector_approval.go`). Beside a sensitive connector (Nessy), a binding's write tool needs `require_approval`: the -config is refused unless each tool it grants only reads (`read_only_tools`) or is held, and a -`tool_patterns` binding needs an entry such as `*` that matches each pattern as written +config is refused unless each tool it grants only reads (`read_only_tools`, or an http tool's +`read_only` at the digest the grant pins: one granted by name or at another revision's digest +does not) or is held, and a `tool_patterns` binding needs an entry such as `*` that matches each pattern as written (`api/configs.go`, `sensitiveBindingsComplaint`). In agent.yaml it is `require_approval:` on the connector entry. Tools a caller declares at createSession are not checked. The caller runs them, or a person's device does (`executor: client`). The router sends a client tool's diff --git a/acceleration/internal/api/configs.go b/acceleration/internal/api/configs.go index dac0637136..4564cf8037 100644 --- a/acceleration/internal/api/configs.go +++ b/acceleration/internal/api/configs.go @@ -16,6 +16,7 @@ import ( "time" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" "github.com/GetStream/Vision-Agents/acceleration/internal/egress" "github.com/GetStream/Vision-Agents/acceleration/internal/guardrail" @@ -1130,13 +1131,39 @@ func bindingSendsOut(binding store.ConnectorBinding, manifest core.Manifest) ([] return unheld, len(unheld) > 0 } for _, tool := range binding.Tools { - if manifest.SendsOutTool(tool.Name) && !binding.RequiresApproval(tool.Name) { + if grantSendsOut(manifest, tool) && !binding.RequiresApproval(tool.Name) { unheld = append(unheld, tool.Name) } } return unheld, len(unheld) > 0 } +// grantSendsOut reports whether the tool that grant names may send data out of the conversation +// (core.Manifest.SendsOutTool), with an http tool judged as the grant pins it: a session opens +// one only at the digest its grant pins (httpsource.Source.Open), and the digest covers its +// method, path and read_only (httpsource.ToolSchemaDigest). So an http tool that only reads at +// the latest revision still sends out when the grant pins no digest, which a session pins on +// first use at the revision its connection is on, or another revision's, such as a POST that +// revision 2 turned into a read-only GET while a connection stays on revision 1 (AI-3675). An +// mcp tool is judged at the latest revision alone, as its read_only_tools say what the server's +// tool does, whatever revision lists it. +func grantSendsOut(manifest core.Manifest, grant store.ToolGrant) bool { + if source := core.HTTPSource(manifest.Sources); source != nil { + for _, tool := range source.HTTPTools { + if tool.Name != grant.Name { + continue + } + // The digest is JSON of strings and maps, which always encodes: an error is no + // digest, which pins nothing. + digest, err := httpsource.ToolSchemaDigest(tool) + if err != nil || digest != grant.SchemaDigest { + return true + } + } + } + return manifest.SendsOutTool(grant.Name) +} + // holdsPattern reports whether the binding's require_approval holds every tool a tool pattern // matches: an entry does when it matches the pattern as written and has no wildcard or escape // but *, such as * or create_* for create_*, as each * then also matches what the pattern's diff --git a/acceleration/internal/api/configs_test.go b/acceleration/internal/api/configs_test.go index d6042c988e..d0a9cf018c 100644 --- a/acceleration/internal/api/configs_test.go +++ b/acceleration/internal/api/configs_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/json" "fmt" + "maps" "net/http" "slices" "strings" @@ -15,6 +16,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/providers" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/stt" ) @@ -2423,6 +2425,66 @@ func (s *ConfigsSuite) TestReadOnlyIsTheConnectorsLatestRevisionsAsAConfigSaveCh s.Len(value(created.Connectors), 2) } +// AI-3675, from AI-3674's Q1: revision 1's tool x is a POST, revision 2 makes it a read-only GET, +// and a fixed connection stays on revision 1, validated there. A session opens x only at the +// digest its grant pins, which covers method and read_only, so x reads only for a grant pinned to +// revision 2's digest: the connection's x, at revision 1's digest, lists as not read_only, a +// config granting it at that digest or by name is refused beside nessy, and one granting it at +// revision 2's digest, which that connection never opens, is accepted. A connection validated at +// revision 2 lists x as read_only. Each revision also has y, a read-only GET whose digest is +// neither grant's. +func (s *ConfigsSuite) TestAnHTTPToolReadsOnlyAtTheDigestItsGrantPins() { + s.useInternalApp() + ctx := context.Background() + id := "custom_t" + strings.ReplaceAll(s.utils.uuid(), "-", "") + post := core.HTTPTool{Name: "x", Description: "Calls the API.", Method: http.MethodPost, Path: "/x"} + get := core.HTTPTool{Name: "x", Description: "Calls the API.", Method: http.MethodGet, Path: "/x", ReadOnly: true} + // linear.yaml's manifest with an http source in place of its mcp one: the suite registers + // oauth2_code alone, which a custom http connector cannot have (core.CustomManifest). + linear, err := s.store.ConnectorDefinitions.Latest(ctx, s.customerID(), "linear") + s.Require().NoError(err) + connectionAt := func(tool core.HTTPTool) (string, string) { + manifest := linear.Manifest + manifest.ID = id + manifest.Endpoints = maps.Clone(manifest.Endpoints) + manifest.Endpoints[core.SourceKindHTTP] = "https://8.8.8.8/api" + manifest.Sources = []core.SourceRule{{Kind: core.SourceKindHTTP, Endpoint: core.SourceKindHTTP, HTTPTools: []core.HTTPTool{ + {Name: "y", Description: "Calls the API.", Method: http.MethodGet, Path: "/y", ReadOnly: true}, tool}}} + definition, err := s.store.ConnectorDefinitions.Revise(ctx, s.customerID(), manifest) + s.Require().NoError(err) + connection := &store.ConnectorConnection{CustomerID: s.customerID(), ConnectorID: id, + DefinitionRevision: definition.Revision, OwnerType: store.OwnerApp, AuthScheme: "oauth2_code"} + s.Require().NoError(s.store.ConnectorConnections.Insert(ctx, s.connectors, connection)) + digest, err := httpsource.ToolSchemaDigest(tool) + s.Require().NoError(err) + s.Require().NoError(s.store.ConnectorConnections.SetTools(ctx, s.customerID(), connection.ID, + []store.ConnectorTool{{Name: "x", InputSchema: map[string]any{"type": "object"}, SchemaDigest: digest}}, "digest", time.Now())) + return connection.ID, digest + } + pinned, atRevision1 := connectionAt(post) + current, atRevision2 := connectionAt(get) + fixed := func(grant map[string]any) map[string]any { + return map[string]any{"name": "api", "connector_id": id, + "connection": map[string]any{"type": "fixed", "connection_id": pinned}, "tools": []map[string]any{grant}} + } + + s.Equal(map[string]bool{"x": false}, s.readOnlyTools(pinned)) + s.Equal(map[string]bool{"x": true}, s.readOnlyTools(current)) + for name, binding := range map[string]map[string]any{ + "at revision 1's digest": fixed(map[string]any{"name": "x", "schema_digest": atRevision1}), + "by name": sessionGranting(id, "api", "x"), + } { + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/configs", map[string]any{ + "name": "triage", "connectors": []map[string]any{sessionNessy("customers"), binding}}) + + s.Equal(http.StatusBadRequest, status, name) + s.Contains(failure, `"api" x`, name) + } + created := s.createConfig(map[string]any{"name": "athena", "connectors": []map[string]any{ + sessionNessy("customers"), fixed(map[string]any{"name": "x", "schema_digest": atRevision2})}}) + s.Len(value(created.Connectors), 2) +} + // A grant by name does not say which source of a connector a tool comes from, so a tool is // read_only only when every source lists it in read_only_tools or says outbound: false, and the // save beside nessy agrees. The first source lists search_documentation too, the second does not: diff --git a/acceleration/internal/api/connection_tools.go b/acceleration/internal/api/connection_tools.go index 6c45e5bd59..5db5e8b322 100644 --- a/acceleration/internal/api/connection_tools.go +++ b/acceleration/internal/api/connection_tools.go @@ -758,7 +758,8 @@ func (s *Server) listConnectionTools(ctx context.Context, request *connectionReq return nil, err } // The latest revision, not the one the connection pins: it is what a config save checks a - // binding beside a sensitive connector against (SensitiveBindingsComplaint). + // binding beside a sensitive connector against (SensitiveBindingsComplaint), with each + // tool's digest as a grant made from this list pins it (grantSendsOut). // A connector the app can no longer see has no definition: a save skips such a binding, so // no tool of it is a read (read_only false) and the tools are still listed. definition, err := s.store.ConnectorDefinitions.Latest(ctx, connection.CustomerID, connection.ConnectorID) @@ -770,7 +771,8 @@ func (s *Server) listConnectionTools(ctx context.Context, request *connectionReq for _, tool := range connection.CachedTools { tools = append(tools, ConnectionTool{Name: tool.Name, Description: tool.Description, InputSchema: maps.Clone(tool.InputSchema), SchemaDigest: tool.SchemaDigest, - NeedsScopes: slices.Clone(tool.NeedsScopes), ReadOnly: known && !definition.Manifest.SendsOutTool(tool.Name)}) + NeedsScopes: slices.Clone(tool.NeedsScopes), + ReadOnly: known && !grantSendsOut(definition.Manifest, store.ToolGrant{Name: tool.Name, SchemaDigest: tool.SchemaDigest})}) } return &connectionToolsResponse{Body: ConnectionTools{ConnectionID: connection.ID, Tools: tools, Digest: connection.ToolsDigest, CheckedAt: connection.ToolsCheckedAt}}, nil diff --git a/acceleration/internal/api/session_connectors_test.go b/acceleration/internal/api/session_connectors_test.go index aed7a0c470..ea70909376 100644 --- a/acceleration/internal/api/session_connectors_test.go +++ b/acceleration/internal/api/session_connectors_test.go @@ -21,7 +21,9 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/fakeprovider" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/providers" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/apikey" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/bearer" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/mcp" "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" "github.com/GetStream/Vision-Agents/acceleration/internal/session" @@ -54,8 +56,8 @@ func TestSessionConnectorsSuite(t *testing.T) { func (s *SessionConnectorsSuite) SetupSuite() { s.provider = fakeprovider.New(s.T(), fakeprovider.ClientCredentials) s.connectors = core.Registry{ - Schemes: map[string]core.Scheme{bearer.Name: bearer.New()}, - ToolSources: map[string]core.ToolSource{mcp.Kind: mcp.New()}, + Schemes: map[string]core.Scheme{bearer.Name: bearer.New(), apikey.Name: apikey.New()}, + ToolSources: map[string]core.ToolSource{mcp.Kind: mcp.New(), httpsource.Kind: httpsource.New()}, } s.connectorHTTP = s.provider.Client() // A call held for approval waits this long here, ten minutes in production, so a test can @@ -89,6 +91,89 @@ func (s *SessionConnectorsSuite) TestAModelsToolCallReachesTheProviderWithTheCon s.Greater(s.provider.Hits(fakeprovider.PathMCP), before) } +// TestAStalePinNeverRunsAWriteAsARead is AI-3674's Q1 in a session (AI-3675): revision 1 of an +// http connector makes echo a POST, revision 2 a read-only GET, and the app's connection, +// validated at revision 1, stays there. Beside nessy, a config granting echo at revision 1's +// digest is refused, as the POST it runs sends data out. One granting it at revision 2's digest +// is accepted, and its session never runs the POST: revision 1 has no echo at that digest, so +// the model's call reaches nothing. A control without nessy grants echo at revision 1's digest, +// and its session runs the POST. +func (s *SessionConnectorsSuite) TestAStalePinNeverRunsAWriteAsARead() { + s.useApp(s.data.createAppAdmitting(store.AppSettings{InternalConnectors: new(true)})) + id := "custom_api" + strings.ReplaceAll(s.utils.uuid(), "-", "") + echo := core.HTTPTool{Name: "echo", Description: "Says the text back.", Method: http.MethodPost, Path: "/echo", + Parameters: map[string]core.HTTPParameter{"text": {Type: "string", Required: true}}} + s.reviseHTTP(id, echo) + connection, atRevision1 := s.keyConnection(id) + echo.Method, echo.ReadOnly = http.MethodGet, true + s.reviseHTTP(id, echo) + atRevision2, err := httpsource.ToolSchemaDigest(echo) + s.Require().NoError(err) + stored, err := s.store.ConnectorConnections.Get(context.Background(), s.customerID(), connection) + s.Require().NoError(err) + s.Require().Equal(1, stored.DefinitionRevision, "the connection stays on revision 1") + fixedAt := func(digest string) map[string]any { + return s.binding("crm", id, "fixed", connection, map[string]any{"name": "echo", "schema_digest": digest}) + } + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/configs", map[string]any{ + "name": "stale-" + s.utils.uuid(), "llm": "connecting/connector-model", + "connectors": []map[string]any{fixedAt(atRevision1), sessionNessy("customers")}}) + s.Equal(http.StatusBadRequest, status, failure) + s.Contains(failure, `"crm" echo`) + + before := len(s.provider.APIRequests()) + read := s.client.createSession(s.session(s.config(fixedAt(atRevision2), sessionNessy("customers")), nil)) + events := s.client.opens("/v1/agents/sessions/" + read.Id + "/events") + s.Require().Equal(http.StatusOK, s.serverClient.actingFor(s.client).do(http.MethodPost, "/v1/agents/sessions/"+read.Id+"/respond", + RespondRequest{Text: "ask the crm", RequestId: pointerTo(s.utils.uuid())}, nil)) + unavailable := map[string]any{} + for frame := s.await(events, "connector_unavailable"); ; frame = s.await(events, "connector_unavailable") { + unavailable[fmt.Sprint(frame["name"])] = frame["reason"] + if len(unavailable) == 2 { + break + } + } + s.Equal("tool_unavailable", unavailable["crm"], "revision 1 offers no echo at revision 2's digest") + s.await(events, "responded") + s.Len(s.provider.APIRequests(), before, "nothing reached the API") + + write := s.client.createSession(s.session(s.config(fixedAt(atRevision1)), nil)) + ran := s.toolRanOn(s.serverClient.actingFor(s.client), s.client.opens("/v1/agents/sessions/"+write.Id+"/events"), write.Id) + s.Equal("ok", ran["result"]) + requests := s.provider.APIRequests()[before:] + s.Require().Len(requests, 1) + s.Equal(http.MethodPost, requests[0].Method, "the session runs revision 1's echo") +} + +// reviseHTTP stores the next revision of connector id, an http connector at the fake's API +// taking its api_key, with tool as its one tool. +func (s *SessionConnectorsSuite) reviseHTTP(id string, tool core.HTTPTool) { + manifest := core.Manifest{ID: id, Name: "API", Schemes: []string{apikey.Name}, + Endpoints: map[string]string{core.SourceKindHTTP: s.provider.URL + fakeprovider.PathAPI}, + Sources: []core.SourceRule{{Kind: core.SourceKindHTTP, Endpoint: core.SourceKindHTTP, HTTPTools: []core.HTTPTool{tool}}}} + _, err := s.store.ConnectorDefinitions.Revise(context.Background(), s.customerID(), manifest) + s.Require().NoError(err) +} + +// keyConnection is a validated connection of the app's to connector holding the fake's API key, +// and the digest its tools list echo at. +func (s *SessionConnectorsSuite) keyConnection(connector string) (string, string) { + var created Connection + s.Require().Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/connections", + withScheme(appOwned(connector), apikey.Name), &created)) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/agents/connections/"+created.ID+"/credentials", + map[string]any{"expected_revision": 1, "values": map[string]string{ + apikey.SuppliedKey: s.provider.APIKey, apikey.SuppliedHeader: fakeprovider.APIKeyHeader}}, nil)) + var validation ConnectionValidation + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/connections/"+created.ID+"/validate", nil, &validation)) + s.Require().Equal(validationConnected, string(validation.Status), validation.Error) + var tools ConnectionTools + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/connections/"+created.ID+"/tools", nil, &tools)) + s.Require().Len(tools.Tools, 1) + return created.ID, tools.Tools[0].SchemaDigest +} + // TestAToolCallAnswered400KeepsAStaticTokenConnected is a control for AI-1052: only a validate // moves a bearer connection on a 4xx; a tool call keeps the 401-only rule (core.Transports), as // on base (probe on 599298c6: status connected). diff --git a/acceleration/internal/connectors/core/AGENTS.md b/acceleration/internal/connectors/core/AGENTS.md index 1079219095..5476bcf53e 100644 --- a/acceleration/internal/connectors/core/AGENTS.md +++ b/acceleration/internal/connectors/core/AGENTS.md @@ -55,7 +55,7 @@ A manifest has `sources`, a `channel` block, or both: Linear has only `sources`, `sensitive: true` marks a connector that reads private data, and `sources[].outbound: false` says a source offers only tools that read, and `sources[].read_only_tools` names the ones that read on a source that also offers tools that write; left out, a tool may write and counts as sending data out. A config binding a sensitive connector is refused beside any binding granting a tool that may send out (`providers/AGENTS.md`, `sensitiveBindingsComplaint`). -A source of kind `http` (`SourceKindHTTP`, `http_tools.go`) lists its own tools in `sources[].http_tools`: each a name, a description, a method, a path under the source's endpoint with `{name}` placeholders, scalar `parameters` and `read_only`. `read_only` is allowed only on GET and HEAD, and it is where an http source says a tool only reads: `read_only_tools` and `outbound: false` are refused on one, and so is `sources[].tools` (`needs_scopes`), which an http source never reads. A manifest has at most one http source, as only the first is read (`HTTPSource`). A parameter or source header named as a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method`, in any case) is refused, so a read-only GET cannot be run as a write. A custom connector is an MCP endpoint or an http `base_url` with tools (`CustomManifest`), under the endpoint role `http`. `sources/http` runs its tools. +A source of kind `http` (`SourceKindHTTP`, `http_tools.go`) lists its own tools in `sources[].http_tools`: each a name, a description, which may not be empty (a session refuses a tool with none, `harness.Tools.Validate`), a method, a path under the source's endpoint with `{name}` placeholders, scalar `parameters` and `read_only`. `read_only` is allowed only on GET and HEAD, and it is where an http source says a tool only reads: `read_only_tools` and `outbound: false` are refused on one, and so is `sources[].tools` (`needs_scopes`), which an http source never reads. A manifest has at most one http source, as only the first is read (`HTTPSource`). A parameter or source header named as a method override (`X-HTTP-Method-Override`, `X-HTTP-Method`, `X-Method-Override`, `_method`, in any case) is refused, so a read-only GET cannot be run as a write. A custom connector is an MCP endpoint or an http `base_url` with tools (`CustomManifest`), under the endpoint role `http`. `sources/http` runs its tools, and its `Open` holds a source to these rules again (`CheckHTTPSource`). | Term | What it is | In code | | --- | --- | --- | @@ -166,7 +166,7 @@ client.Do(request) the egress client of one connection - **One client per connection, a copy per caller.** `Transports.Client` builds the client once per `ConnectionRef` and returns a copy that shares its connection pool, so a caller that replaces its copy's `Transport` changes nothing for the others. `Transports.Close(ref)` drops it and closes its idle connections, for the delete and disconnect paths to call. `cmd/router` builds one `Transports` and hands it to the API (`api.Options.ConnectorTransports`), whose validate endpoint is one caller; the session's dispatcher (`session.ManagerOptions.Connectors`) shares it, and `deleteConnection` calls `Close`. A copy held past `Close` still asks the resolver first, which refuses a connection that is gone. A client nothing asked for or sent with for `idleAfter` (90 s, `DefaultTransport`'s `IdleConnTimeout`, by when it holds no idle socket) is dropped the next time a client is built, at most once per `idleAfter`, so every replica forgets connections it no longer uses. Check: `go test -run 'TestTransportsSuite/(TestOneConnection|TestClosing|TestReplacing|TestAClientUnused)' ./internal/connectors/core` and `go test -tags integration -run TestTransportSuite/TestAClientHeldPastADelete ./internal/connectors/resolver`. - **`Retrieve` can run before egress refuses.** The dial check comes after `Wrap`, so a refresh for a host that resolves to a private address still runs; the token never leaves the router. When `Retrieve` itself must not run, call `egress.ValidatePublicHTTPSURL` on the endpoint first. - A scheme's TLS client certificate (`mtls`, `tls_scheme`) is not built yet; it belongs to this one client per connection. -- **A request records what it saw for whoever asked (`Exchange`, `records.go`).** A context made by `WithExchange` gets told whether a request left with a credential, the provider's last status, the `Resolver`'s refusal and a client timeout; nothing else is kept, never a header, a body or a credential. `Exchange.Redact` takes out of a text, such as the tool source's error, what the error body has taken out: the last request's path and query and its credential's strings, held only inside a function so nothing prints them (AI-1244). The session's dispatcher reads it to say how a tool call failed in the invocation log, because a tool source's error does not say whether anything was sent and the MCP client reports a 401 only as its status text. A context without one records nothing. Example: a provider answering 401 to a call is `customer_auth`; arguments the source refuses before sending are `denied`. Check: `go test -tags integration -run TestInvocationLogSuite ./internal/session`. +- **A request records what it saw for whoever asked (`Exchange`, `records.go`).** A context made by `WithExchange` gets told whether a request left with a credential, the provider's last status, the `Resolver`'s refusal and a client timeout; nothing else is kept, never a header, a body or a credential. `Exchange.Redact` takes out of a text, such as the tool source's error, what the error body has taken out: the last request's path and query and its credential's strings, held only inside a function so nothing prints them (AI-1244). `Exchange.RedactCredential` takes out the credential's secret values alone, for an answer the model reads, such as an http tool's 2xx: not a name the secret holds, such as api_key's header name (`SecretValuer`). The session's dispatcher reads it to say how a tool call failed in the invocation log, because a tool source's error does not say whether anything was sent and the MCP client reports a 401 only as its status text. A context without one records nothing. Example: a provider answering 401 to a call is `customer_auth`; arguments the source refuses before sending are `denied`. Check: `go test -tags integration -run TestInvocationLogSuite ./internal/session`. - **Who caused a grant change rides on the context (`Correlation`, `records.go`).** The API puts the request's `X-Request-Id` on every request's context, and the session's dispatcher adds the session's id, both when a binding is opened and when a tool is called; the resolver copies both onto the audit rows it writes. A session's turns run on the context of the request that created it, so for an incognito session the dispatcher drops the request id too, on open and on call, and its rows carry neither. Check: `go test -tags integration -run TestResolverSuite/TestAuditOfARefreshIsOne ./internal/connectors/resolver` and `go test -tags integration -run 'TestInvocationLogSuite/Test(AnIncognito|ARecorded)' ./internal/session`. ## Tests diff --git a/acceleration/internal/connectors/core/error_body.go b/acceleration/internal/connectors/core/error_body.go index 17d7cebb48..14bfe07bbf 100644 --- a/acceleration/internal/connectors/core/error_body.go +++ b/acceleration/internal/connectors/core/error_body.go @@ -1,6 +1,7 @@ package core import ( + "cmp" "encoding/json" "io" "net/http" @@ -131,17 +132,34 @@ type redaction []string // "Cannot POST /primary/mcp", and a provider may answer "invalid token ". func redactionOf(request *http.Request, credential AccessCredential) redaction { found := []string{request.URL.RequestURI(), request.URL.EscapedPath(), request.URL.Path, request.URL.RawQuery} + return redactionFrom(append(found, secretStrings(credential)...)) +} + +// secretStrings is each string in the credential's secret (AccessCredential.Secret): bearer's +// token, api_key's header and key. +func secretStrings(credential AccessCredential) []string { var secret any - if json.Unmarshal(credential.Secret(), &secret) == nil { - found = appendStrings(found, secret) + if json.Unmarshal(credential.Secret(), &secret) != nil { + return nil + } + return appendStrings(nil, secret) +} + +// secretValues is each secret value of the credential scheme issued: its SecretValues when it +// is a SecretValuer, else every string of the secret (secretStrings). +func secretValues(scheme Scheme, credential AccessCredential) []string { + if valuer, ok := scheme.(SecretValuer); ok { + return valuer.SecretValues(credential) } - return redactionFrom(found) + return secretStrings(credential) } -// redactionFrom is the redaction of each of found longer than a byte, in order, each as it is, +// redactionFrom is the redaction of each of found longer than a byte, each as it is, // URL-escaped and JSON-escaped: a token request's form body is urlencoded (url.Values.Encode, // QueryEscape), and its basic auth carries the client secret QueryEscaped (RFC 6749 section // 2.3.1), so a provider may echo either form. A JSON body escapes what it echoes (jsonEscaped). +// The longest is taken out first, so a string that holds another goes out whole: api_key's key +// X-Key-9f8e holds its header X-Key, which taken out first would leave -9f8e (AI-3675 S1.2). func redactionFrom(found []string) redaction { var r redaction for _, s := range found { @@ -156,6 +174,7 @@ func redactionFrom(found []string) redaction { } } } + slices.SortStableFunc(r, func(a, b string) int { return cmp.Compare(len(b), len(a)) }) return r } diff --git a/acceleration/internal/connectors/core/http_tools.go b/acceleration/internal/connectors/core/http_tools.go index 208a523c9d..103ace24c0 100644 --- a/acceleration/internal/connectors/core/http_tools.go +++ b/acceleration/internal/connectors/core/http_tools.go @@ -1,12 +1,15 @@ package core import ( + "errors" "fmt" "maps" "net/http" "regexp" "slices" "strings" + + "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) // SourceKindHTTP is the sources[].kind of the http source: the tools are the ones the manifest @@ -100,6 +103,21 @@ var ( httpParameterName = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,64}$`) ) +// CheckHTTPSource is every rule of Manifest.Validate an http source breaks, or nil: the same +// rules (checkHTTPSource), for the http tool source to hold a manifest it opens to again, so a +// stored one that skipped validation cannot offer a tool that names a method override or writes +// while saying it reads (AI-3675). +func CheckHTTPSource(source SourceRule) error { + var errs []error + checkHTTPSource(func(field, format string, args ...any) { + errs = append(errs, fmt.Errorf("%s: %s", field, fmt.Sprintf(format, args...))) + }, "sources[http]", source) + if len(errs) > 0 { + return stack.Wrap(errors.Join(errs...)) + } + return nil +} + // checkHTTPSource refuses an http source whose tools a session could not offer or that could // write while saying they read. field names the source. func checkHTTPSource(fail func(field, format string, args ...any), field string, source SourceRule) { @@ -130,6 +148,11 @@ func checkHTTPSource(fail func(field, format string, args ...any), field string, fail(field+".name", "%q is named twice", tool.Name) } named[tool.Name] = true + // Why: a session refuses a tool with no description (harness.Tools.Validate), since the + // model would never know when to use it; refused here, the sync says so, not a session. + if tool.Description == "" { + fail(field+".description", "is empty: the model reads it to know when to use the tool") + } if len(tool.Description) > maxHTTPToolDescription { fail(field+".description", "is over %d bytes", maxHTTPToolDescription) } diff --git a/acceleration/internal/connectors/core/http_tools_test.go b/acceleration/internal/connectors/core/http_tools_test.go index 5ab0f320db..7007ff7335 100644 --- a/acceleration/internal/connectors/core/http_tools_test.go +++ b/acceleration/internal/connectors/core/http_tools_test.go @@ -80,7 +80,6 @@ func (s *HTTPSourceSuite) TestAValidHTTPSourceIsAccepted() { "a boolean": withTool(func(t *HTTPTool) { t.Parameters["days"] = HTTPParameter{Type: "boolean"} }), "a name of 63 with capitals and -": withTool(func(t *HTTPTool) { t.Name = "Get-" + strings.Repeat("x", 59) }), "a description of 1000 bytes": withTool(func(t *HTTPTool) { t.Description = strings.Repeat("d", 1000) }), - "no description": withTool(func(t *HTTPTool) { t.Description = "" }), "a path of 2048 bytes": withTool(func(t *HTTPTool) { t.Path = "/{city}/" + strings.Repeat("p", 2040) }), "the root path": withTool(func(t *HTTPTool) { t.Path, t.Parameters = "/", nil }), "a {name} inside a segment": withTool(func(t *HTTPTool) { t.Path = "/files/{city}.json" }), @@ -166,8 +165,9 @@ func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { "needs_scopes on a source with no tool": {noTool(func(r *SourceRule) { r.Tools = []ToolRule{{Name: "x", NeedsScopes: []string{"read"}}} }), `sources[0].tools: is not set on an http source`}, "read_only_tools on a source with no tool": {noTool(func(r *SourceRule) { r.ReadOnlyTools = []string{"x"} }), `sources[0].read_only_tools: is not set on an http source`}, "an override header on a source with no tool": {noTool(func(r *SourceRule) { r.Headers = map[string]string{"X-HTTP-Method": "PUT"} }), `names a method override`}, - "a description over 1000": {withTool(func(t *HTTPTool) { t.Description = strings.Repeat("d", 1001) }), `http_tools[0].description: is over 1000 bytes`}, - "129 tools": {httpManifest(tools(129)...), `sources[0].http_tools: has 129 tools, over 128`}, + "no description": {withTool(func(t *HTTPTool) { t.Description = "" }), `http_tools[0].description: is empty`}, + "a description over 1000": {withTool(func(t *HTTPTool) { t.Description = strings.Repeat("d", 1001) }), `http_tools[0].description: is over 1000 bytes`}, + "129 tools": {httpManifest(tools(129)...), `sources[0].http_tools: has 129 tools, over 128`}, "http_tools on an mcp source": {Manifest{ID: "example", Revision: 1, Name: "Example", Schemes: []string{"bearer"}, Endpoints: map[string]string{SourceKindMCP: "https://api.example.com/mcp"}, Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP, HTTPTools: []HTTPTool{forecast()}}}}, @@ -193,11 +193,11 @@ func (s *HTTPSourceSuite) TestEveryToolIsChecked() { func (s *HTTPSourceSuite) TestAnHTTPSourceParsesFromYAML() { parsed, err := ParseManifest(minimal("endpoints:\n http: https://api.example.com/v1\nsources:\n - kind: http\n endpoint: http\n" + - " http_tools:\n - name: get_forecast\n method: GET\n path: /forecast/{city}\n read_only: true\n" + + " http_tools:\n - name: get_forecast\n description: The forecast for a city.\n method: GET\n path: /forecast/{city}\n read_only: true\n" + " parameters:\n city: {type: string, required: true}\n")) s.Require().NoError(err) - s.Equal([]HTTPTool{{Name: "get_forecast", Method: "GET", Path: "/forecast/{city}", ReadOnly: true, + s.Equal([]HTTPTool{{Name: "get_forecast", Description: "The forecast for a city.", Method: "GET", Path: "/forecast/{city}", ReadOnly: true, Parameters: map[string]HTTPParameter{"city": {Type: "string", Required: true}}}}, HTTPSource(parsed.Sources).HTTPTools) } diff --git a/acceleration/internal/connectors/core/provider_text_test.go b/acceleration/internal/connectors/core/provider_text_test.go index a046c34fa4..743f646f77 100644 --- a/acceleration/internal/connectors/core/provider_text_test.go +++ b/acceleration/internal/connectors/core/provider_text_test.go @@ -49,6 +49,13 @@ func (s *LoggedDescriptionSuite) TestAJSONEscapedEchoOfASecretIsRedacted() { s.Equal("go [redacted], php [redacted], plain [redacted], plain php [redacted]", core.LoggedDescription(text, secret)) } +// TestASecretHoldingAnotherIsTakenOutWhole (AI-3675 S1.2): api_key's key may hold its header +// name, and taking the name out first would leave the rest of the key. +func (s *LoggedDescriptionSuite) TestASecretHoldingAnotherIsTakenOutWhole() { + s.Equal("seen [redacted], header [redacted]", + core.LoggedDescription("seen X-Key-9f8e7d6c5b, header X-Key", "X-Key", "X-Key-9f8e7d6c5b")) +} + // TestASecretOfOneByteIsLeftAlone: a byte alone names nothing, and taking it out would take // out every such byte, as the Exchange's redaction leaves it. func (s *LoggedDescriptionSuite) TestASecretOfOneByteIsLeftAlone() { @@ -102,6 +109,13 @@ func (s *LoggedMessageSuite) TestAnUnreachedErrorAddsWhatFailed() { s.Equal(`http: crm__lookup: the API could not be reached: Get "https://crm.example": EOF`, core.LoggedMessage(err, nil)) } +// R2.1 of AI-3674: an UnreachedError with no cause is its Message alone on the line. +func (s *LoggedMessageSuite) TestAnUnreachedErrorWithNoCauseIsItsMessage() { + err := stack.Wrap(&core.UnreachedError{Message: "http: crm__lookup: the API could not be reached"}) + + s.Equal("http: crm__lookup: the API could not be reached", core.LoggedMessage(err, nil)) +} + func (s *LoggedMessageSuite) TestNoErrorIsNoMessage() { s.Empty(core.LoggedMessage(nil, nil)) } diff --git a/acceleration/internal/connectors/core/records.go b/acceleration/internal/connectors/core/records.go index b81c7f7010..cce31602c4 100644 --- a/acceleration/internal/connectors/core/records.go +++ b/acceleration/internal/connectors/core/records.go @@ -61,6 +61,9 @@ type Exchange struct { // redact is Redact's redaction for the last request that left, nil when none did. A // function, so that %v of an Exchange prints no secret (AGENTS.md «Secrets never print»). redact func(string) string + // redactCredential is RedactCredential's redaction for the last request that left, nil + // when none did. A function for the same reason as redact. + redactCredential func(string) string } type exchangeKey struct{} @@ -71,6 +74,16 @@ func WithExchange(ctx context.Context) (context.Context, *Exchange) { return context.WithValue(ctx, exchangeKey{}, e), e } +// Observed is ctx and the Exchange it carries, or ctx carrying a new one when it carries none +// (WithExchange), for a tool source that redacts what it returns for a call (Exchange.Redact) +// whoever called it. +func Observed(ctx context.Context) (context.Context, *Exchange) { + if e := exchangeOf(ctx); e != nil { + return ctx, e + } + return WithExchange(ctx) +} + // exchangeOf is the Exchange ctx carries, nil when it carries none. func exchangeOf(ctx context.Context) *Exchange { e, _ := ctx.Value(exchangeKey{}).(*Exchange) @@ -131,6 +144,21 @@ func (e *Exchange) Redact(text string) string { return e.redact(text) } +// RedactCredential is text, such as a 2xx answer a tool source returns for the call, with +// each secret value of the credential the last request was sent with taken out, as Redact takes +// them out, but its path and query kept, and a name the secret holds, such as api_key's header +// name (SecretValuer): an answer names the resource it is about, and may name the header. Text is +// unchanged when no request left. Example: an API answering 200 with "your key is " +// says "your key is [redacted]". +func (e *Exchange) RedactCredential(text string) string { + e.mu.Lock() + defer e.mu.Unlock() + if e.redactCredential == nil { + return text + } + return e.redactCredential(text) +} + // WWWAuthenticate is the WWW-Authenticate of the last answer, its values joined with ", " // (RFC 9110 section 5.3), when that answer was a 4xx or a 5xx; "" otherwise. func (e *Exchange) WWWAuthenticate() string { @@ -184,9 +212,10 @@ func (e *Exchange) refused(err error) { e.credential = err } -// sending records that a request to host is leaving with a credential, and what of it and -// that credential Redact takes out (redaction). -func (e *Exchange) sending(host string, redact redaction) { +// sending records that a request to host is leaving with a credential, what of it and that +// credential Redact takes out (redaction), and what of the credential alone RedactCredential +// takes out (secret). +func (e *Exchange) sending(host string, redact, secret redaction) { if e == nil { return } @@ -194,6 +223,7 @@ func (e *Exchange) sending(host string, redact redaction) { defer e.mu.Unlock() e.sent, e.host = true, host e.redact = func(text string) string { return redact.apply(text, true) } + e.redactCredential = func(text string) string { return secret.apply(text, true) } } // answered records how a request that left ended: with the provider's status, or with err. diff --git a/acceleration/internal/connectors/core/scheme.go b/acceleration/internal/connectors/core/scheme.go index 8a79e36100..a618011b43 100644 --- a/acceleration/internal/connectors/core/scheme.go +++ b/acceleration/internal/connectors/core/scheme.go @@ -53,6 +53,16 @@ type Static interface { StaticCredential() } +// SecretValuer is a Scheme whose secret holds a name beside its secret values, such as +// api_key's header name beside its key. Exchange.RedactCredential takes out of an answer the +// values alone: an API's answer may name its own header, as its docs do, and that name is no +// secret (AI-3675 R1.1). It is optional: every string of the secret of a scheme that does not +// implement it is a secret value. +type SecretValuer interface { + // SecretValues is each string of c's secret that is a secret value. + SecretValues(c AccessCredential) []string +} + // IsStatic reports whether the scheme schemes names name is Static. An unknown name is not. func IsStatic(schemes map[string]Scheme, name string) bool { _, ok := schemes[name].(Static) diff --git a/acceleration/internal/connectors/core/transport.go b/acceleration/internal/connectors/core/transport.go index 25215fa2ae..505813420e 100644 --- a/acceleration/internal/connectors/core/transport.go +++ b/acceleration/internal/connectors/core/transport.go @@ -213,11 +213,12 @@ func (c *credentialed) RoundTrip(request *http.Request) (*http.Response, error) // What of this request and its credential an error must not keep, for its body // (recordBody) and for Redact. Only for a request whose context carries an Exchange, // as the body below: no other caller reads it. - var redact redaction + var redact, secret redaction if exchange != nil { redact = redactionOf(request, credential) + secret = redactionFrom(secretValues(c.scheme, credential)) } - exchange.sending(request.URL.Host, redact) + exchange.sending(request.URL.Host, redact, secret) response, err := c.scheme.Wrap(c.base, credential).RoundTrip(request) if err != nil { exchange.answered(0, err) diff --git a/acceleration/internal/connectors/fakeprovider/AGENTS.md b/acceleration/internal/connectors/fakeprovider/AGENTS.md index 788a9167ba..5ad5e2e850 100644 --- a/acceleration/internal/connectors/fakeprovider/AGENTS.md +++ b/acceleration/internal/connectors/fakeprovider/AGENTS.md @@ -19,6 +19,7 @@ That is the whole setup. The server closes when the test ends (`t.Cleanup`). It - `TeamID`, `UserID`, `RealmID`, `Shop`, `IdentityURL`: the synthetic identities the vendor-shaped personalities report. - `srv.AnswerMCP(status)`: every `/mcp` request is answered with `status` and its reason phrase as plain text, whatever token it carries, until `srv.AnswerMCP(0)`. GitHub's MCP server answers a wrong token with 400 Bad Request (volt E2E F60), where the fake answers 401. - `srv.InstructMCP(text)`: `server/discover` answers with `instructions` about using the tools, until `srv.InstructMCP("")`. +- An HTTP API at `srv.URL + PathAPI` (`/rest`, `api.go`), which an http connector's tools call (`sources/http`): every method on every path under it. It takes `srv.APIKey` in `APIKeyHeader` (`X-Api-Key`, as an `api_key` connection sends it) and answers 401 without it. `/rest/bytes/` answers n bytes of text, then `?then=` bytes that are not UTF-8; `/rest/echo-credential` answers 403 echoing the key and the `Authorization` it got, and the same body as a 200 with `?status=200`; any other path answers 200 `ok`. `srv.APIRequests()` are the requests that reached it, refused ones too, each with its method, request-line URI (escaped as sent), headers and body. For AC-6 and AC-9 of AI-3669. - `srv.SwitchAccount()`: every later consent is by another user of the same workspace (its id is returned; `UserID` keeps the first). Grants already made keep their user. For an account-switch test (T17). - Under `SlackChannel`: `srv.Deliver(url, signingSecret, body, retry)` posts an Events API event signed as Slack signs it, with `X-Slack-Retry-Num` when `retry` is 1 to 3; `srv.DeliverInteraction(url, signingSecret, form)` posts an interaction, such as `block_actions`, as an `application/x-www-form-urlencoded` form signed the same way (that Slack signs interactions so is unverified), and returns the headers it sent; `srv.InstallBot()` is a bot token the server issued, with no expiry, for a connection's stored credentials; `srv.RevokeBot(token)` ends its grant; `srv.FailPosts(n)` has the next n posts answer 503; `srv.Posts()` are the replies `chat.postMessage` took, each with the token it came with (compare it with `==`). - Under `MCPEvents`: `server/discover` names the `events` capability, `events/subscribe` checks the `whsec_` secret, verifies the callback by posting a signed `verification` challenge and needing it echoed, then subscribes (or refreshes) under the token's grant with `refreshBefore` `EventsTTL` (1 h) away, and `events/unsubscribe` stops it (`-32011` when there is none). `srv.EventSubscriptions()` reads them back with their secrets; `srv.Emit(event, data)` delivers to every subscription to `event`, signed with each one's own secret, and returns the statuses by subscription id; `srv.DeliverEvent(url, secret, subscriptionID, eventID, event, data)` posts one occurrence signed with any secret, to forge one. `fakeprovider.NewWebhookSecret()` is a `whsec_` secret the server never saw. `srv.GrantEventsFor(d)` grants `d` instead of `EventsTTL`; a negative `d` answers a `refreshBefore` already past. diff --git a/acceleration/internal/connectors/fakeprovider/api.go b/acceleration/internal/connectors/fakeprovider/api.go new file mode 100644 index 0000000000..872ceffe42 --- /dev/null +++ b/acceleration/internal/connectors/fakeprovider/api.go @@ -0,0 +1,79 @@ +package fakeprovider + +import ( + "bytes" + "cmp" + "io" + "net/http" + "strconv" + "strings" +) + +// PathAPI is the root of the fake's HTTP API, which an http connector's tools call +// (internal/connectors/sources/http): every method, on every path under it. Not /api, which is +// the fake Slack's (PathSlackAPI). +const PathAPI = "/rest" + +// APIKeyHeader is the header the API takes APIKey in, as an api_key connection sends it +// (schemes/apikey). X-Api-Key is the scheme contract's own example header. +const APIKeyHeader = "X-Api-Key" + +// APIRequest is one request that reached the API, as it arrived. +type APIRequest struct { + Method string + // URI is the request line's target: the path as it was sent, escaped, and the query. + URI string + Header http.Header + Body string +} + +// APIRequests are the requests that reached the API, in order, whatever they carried. +func (s *Server) APIRequests() []APIRequest { + s.mu.Lock() + defer s.mu.Unlock() + return append([]APIRequest{}, s.apiRequests...) +} + +// api records the request, then answers 401 unless it carries APIKey in APIKeyHeader, and +// otherwise by path: +// +// /rest/bytes/ 200 with n bytes of text ("a" each), then the number of bytes the +// query's then names (none when it names none) that are not UTF-8 +// (0xff each), so a reader that reads past n reads no text +// /rest/echo-credential 403 whose body says the APIKeyHeader and Authorization it got, as an +// API that echoes the request's credential in its error does; with +// ?status=200, the same body as a 200, as one that echoes it in an +// answer does +// anything else 200 "ok" +func (s *Server) api(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + s.mu.Lock() + s.apiRequests = append(s.apiRequests, APIRequest{Method: r.Method, URI: r.RequestURI, Header: r.Header.Clone(), Body: string(body)}) + s.mu.Unlock() + if r.Header.Get(APIKeyHeader) != s.APIKey { + w.WriteHeader(http.StatusUnauthorized) + return + } + path := strings.TrimPrefix(r.URL.Path, PathAPI) + if size, found := strings.CutPrefix(path, "/bytes/"); found { + n, err := strconv.Atoi(size) + then, thenErr := strconv.Atoi(cmp.Or(r.URL.Query().Get("then"), "0")) + if err != nil || n < 0 || thenErr != nil || then < 0 { + w.WriteHeader(http.StatusBadRequest) + return + } + _, _ = io.WriteString(w, strings.Repeat("a", n)) + _, _ = w.Write(bytes.Repeat([]byte{0xff}, then)) + return + } + if path == "/echo-credential" { + status := http.StatusForbidden + if r.URL.Query().Get("status") == "200" { + status = http.StatusOK + } + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"error":"key `+r.Header.Get(APIKeyHeader)+` and `+r.Header.Get("Authorization")+` may not read this"}`) + return + } + _, _ = io.WriteString(w, "ok") +} diff --git a/acceleration/internal/connectors/fakeprovider/fakeprovider.go b/acceleration/internal/connectors/fakeprovider/fakeprovider.go index 6413133f00..eda025ac8f 100644 --- a/acceleration/internal/connectors/fakeprovider/fakeprovider.go +++ b/acceleration/internal/connectors/fakeprovider/fakeprovider.go @@ -246,6 +246,8 @@ type Server struct { RealmID string Shop string IdentityURL string + // APIKey is the key the HTTP API (PathAPI) takes in APIKeyHeader. Synthetic. + APIKey string t testing.TB server *httptest.Server @@ -291,6 +293,8 @@ type Server struct { // mcpHeaders are the headers of every request that reached the MCP endpoint, in order // (MCPHeader). mcpHeaders []http.Header + // apiRequests are the requests that reached the HTTP API, in order (APIRequests). + apiRequests []APIRequest // The fake Slack (slack.go): configuration tokens by token, refresh tokens with whether // they were spent, successful rotations, and apps by id in the order they were made. @@ -368,6 +372,7 @@ func New(t testing.TB, personalities ...Personality) *Server { // Nothing dials it; a manifest only captures it. IdentityURL: "https://login.salesforce.com/id/00D" + strings.ToUpper(synthetic("org")[4:19]) + "/005" + strings.ToUpper(synthetic("user")[5:20]), + APIKey: synthetic("key"), t: t, personalities: map[Personality]bool{}, clients: map[string]*client{}, @@ -552,6 +557,7 @@ func (s *Server) routes() http.Handler { // Streamable HTTP Revisions»). mux.HandleFunc("POST "+PathMCP, s.mcp) mux.HandleFunc("POST "+PathChatPostMessage, s.chatPostMessage) + mux.HandleFunc(PathAPI+"/", s.api) s.slackRoutes(mux) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { s.mu.Lock() diff --git a/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go b/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go index 5cce7d757f..5e5caf1f47 100644 --- a/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go +++ b/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go @@ -1170,3 +1170,49 @@ func (s *FakeProviderSuite) slack(srv *fakeprovider.Server, method, token string s.Require().NoError(json.NewDecoder(response.Body).Decode(&answered)) return answered } + +// The HTTP API answers only APIKey, records every request as it arrived, sizes /bytes/ to n, +// and echoes the credential in /echo-credential's 403, or in its 200 with ?status=200. +func (s *FakeProviderSuite) TestTheHTTPAPITakesItsKeyRecordsEachRequestAndAnswersByPath() { + srv := fakeprovider.New(s.T()) + send := func(method, path, key string) (int, string) { + request, err := http.NewRequest(method, srv.URL+fakeprovider.PathAPI+path, strings.NewReader("sent")) + s.Require().NoError(err) + request.Header.Set(fakeprovider.APIKeyHeader, key) + response, err := srv.Client().Do(request) + s.Require().NoError(err) + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + s.Require().NoError(err) + return response.StatusCode, string(body) + } + + status, _ := send(http.MethodGet, "/items", "another-key") + s.Equal(http.StatusUnauthorized, status) + status, body := send(http.MethodDelete, "/items/..%2Fadmin?q=1", srv.APIKey) + s.Equal(http.StatusOK, status) + s.Equal("ok", body) + status, body = send(http.MethodGet, "/bytes/5", srv.APIKey) + s.Equal(http.StatusOK, status) + s.Equal("aaaaa", body) + status, body = send(http.MethodGet, "/bytes/2?then=3", srv.APIKey) + s.Equal(http.StatusOK, status) + s.Equal("aa\xff\xff\xff", body) + for _, size := range []string{"/bytes/x", "/bytes/-1", "/bytes/1?then=x", "/bytes/1?then=-1"} { + status, _ = send(http.MethodGet, size, srv.APIKey) + s.Equal(http.StatusBadRequest, status, size) + } + status, body = send(http.MethodPost, "/echo-credential", srv.APIKey) + s.Equal(http.StatusForbidden, status) + s.Contains(body, srv.APIKey) + status, body = send(http.MethodGet, "/echo-credential?status=200", srv.APIKey) + s.Equal(http.StatusOK, status) + s.Contains(body, srv.APIKey) + + requests := srv.APIRequests() + s.Require().Len(requests, 10, "the refused ones too") + s.Equal(http.MethodDelete, requests[1].Method) + s.Equal("/rest/items/..%2Fadmin?q=1", requests[1].URI) + s.Equal("sent", requests[1].Body) + s.Equal(srv.APIKey, requests[1].Header.Get(fakeprovider.APIKeyHeader)) +} diff --git a/acceleration/internal/connectors/schemes/apikey/scheme.go b/acceleration/internal/connectors/schemes/apikey/scheme.go index e195252881..81e5effc57 100644 --- a/acceleration/internal/connectors/schemes/apikey/scheme.go +++ b/acceleration/internal/connectors/schemes/apikey/scheme.go @@ -77,6 +77,17 @@ type payload struct { Key string `json:"key"` } +// SecretValues is the key alone (core.SecretValuer): the header it goes in is a name, which an +// API's answer may say, as its docs do. A credential this scheme cannot read has none, and +// Wrap sends no request with it. +func (*Scheme) SecretValues(c core.AccessCredential) []string { + var p payload + if json.Unmarshal(c.Secret(), &p) != nil { + return nil + } + return []string{p.Key} +} + // StaticCredential marks api_key as core.Static: the key is supplied and never renewed, so a // key the provider rejects is replaced, not consented to again. func (*Scheme) StaticCredential() {} diff --git a/acceleration/internal/connectors/sources/http/AGENTS.md b/acceleration/internal/connectors/sources/http/AGENTS.md index 1d50b03ce1..59aaf29eb1 100644 --- a/acceleration/internal/connectors/sources/http/AGENTS.md +++ b/acceleration/internal/connectors/sources/http/AGENTS.md @@ -14,15 +14,19 @@ Discover(ctx, binding) sends nothing: the manifest is the list Open(ctx, binding, grants) alias binding.Name, never holding "__" - client a copy of binding.HTTP whose Timeout is at least 35 s (callTimeout) + source core.CheckHTTPSource again: a rule of validation broken -> error, nothing offered + client a copy of binding.HTTP whose Timeout is at least 35 s (callTimeout); + redirects followed only for GET and HEAD, within binding.HTTP's own policy keep granted by name AND digest unchanged offer alias + "__" + name Toolset.Call(call) unknown name -> error, nothing sent + an undeclared argument -> "an argument is not one of the tool's parameters", nothing sent arguments vs schema -> error, nothing sent URL endpoint (one trailing / dropped) + path, joined as text - {name} the argument, url.PathEscape'd: one segment + {name} the argument, url.PathEscape'd: one segment; a segment holding one that comes + out "", "." or ".." -> "a path parameter is empty, . or ..", nothing sent others GET, HEAD, DELETE -> query; POST, PUT, PATCH -> JSON object body (an empty object when every parameter is in the path) only declared parameters; numbers as the model wrote them @@ -31,14 +35,25 @@ Toolset.Call(call) "http: : the API could not be reached, or its answer did not arrive whole"; the cause behind Unwrap and on the log line (core.LoggedMessage) answer read up to 4 MiB, cut back to a whole rune; not UTF-8 -> "not text" sentence - 2xx text, cut at 32 KiB + marker (core.CutResult); empty -> "The API answered ." - otherwise *core.ToolError "The API answered [: ]", cut the same way + write's 301, 302, 303 + "The API answered ; the request may have run.", a result + 2xx text, the credential taken out (core.Exchange.RedactCredential), cut at 32 KiB + + marker (core.CutResult); empty -> "The API answered ." + otherwise *core.ToolError "The API answered [: ]", redacted with the call's + core.Exchange (credential, path, query), then cut the same way; a write's 307 + or 308 is one ``` ## Rules - **Only through `ResolvedBinding.HTTP`.** The source never builds a client: an opened toolset sends with a copy of the binding's client that differs only in its timeout, so the credential, the 401 renewal (`core/AGENTS.md`, «Transport»), the egress checks and the redirect policy all run. Check: `go test -run 'TestSourceSuite/(TestAGETSends|TestAnAnswerThatIsNotA2xx)' ./internal/connectors/sources/http`. -- **Where a parameter goes is decided (AI-3669, «Decided»).** `{name}` in the path, escaped as one segment; the others in the query of a GET, a HEAD or a DELETE, and in a JSON body of a POST, a PUT or a PATCH. Only the parameters the tool declares are sent, so an argument the model adds goes nowhere. Check: `go test -run 'TestSourceSuite/(TestAGETSends|TestAPOSTSends|TestEachMethod|TestAnArgumentTheTool)' ./internal/connectors/sources/http`. +- **Where a parameter goes is decided (AI-3669, «Decided»).** `{name}` in the path, escaped as one segment; the others in the query of a GET, a HEAD or a DELETE, and in a JSON body of a POST, a PUT or a PATCH. Check: `go test -run 'TestSourceSuite/(TestAGETSends|TestAPOSTSends|TestEachMethod)' ./internal/connectors/sources/http`. +- **An argument the tool does not declare is refused before sending** (AC-6 of AI-3669), with one sentence, so `_method` or `X-HTTP-Method-Override` from the model never goes anywhere and the model does not take the call for one that went with it. Check: `go test -run 'TestSourceSuite/TestAnArgumentTheTool|TestAcceptanceSuite/TestAnOverride' ./internal/connectors/sources/http`. +- **A path value cannot name another resource** (AI-3674, S1.3). The path is judged as it is built: a segment holding a `{name}` that comes out empty (`DELETE /items/` for an empty id: the collection), `.` or `..` (resolved away by RFC 3986 section 5.2.4, also when `{a}{b}` makes `..` of `.` and `.`) is refused before sending. A value with a `/` stays one segment, `../admin` sent as `..%2Fadmin` (AC-6), and an escaped value keeps its `%`, `..%2F` sent as `..%252F`: an API that decodes `%2F` into a `/` before it routes reads another path, which is the API's own reading. Check: `go test -run 'TestSourceSuite/TestAPathValue' ./internal/connectors/sources/http`. +- **Open checks the source again** (`core.CheckHTTPSource`, the rules `Manifest.Validate` holds a stored one to): a tool parameter or a source header named as a method override, or a read_only tool that is not a GET or a HEAD, fails `Open`, so a manifest stored past validation offers nothing. Check: `go test -run 'TestSourceSuite/TestOpenRefuses' ./internal/connectors/sources/http`. +- **Only a read follows a redirect** (AI-3674, R1.6). A GET or a HEAD follows one within the egress client's policy (the same origin and method, so the credential never reaches another origin); any other method gets the 3xx as its answer: a 307 or a 308 as a tool error, and a 301, a 302 or a 303, after which the write may have run (RFC 9110 sections 15.4.2 to 15.4.4), as the result "The API answered ; the request may have run.", so the model does not call it again as if it failed (AI-3675, R1.2). A write's method and path are what the manifest fixes, and net/http sends a POST, PUT or PATCH body again on a 307 or 308, so a followed one would run the write, maybe twice, at a path the manifest does not name. A client with no policy of its own stops at net/http's 10. Check: `go test -run 'TestSourceSuite/(TestOnlyARead|TestARedirectToAnother|TestAClientWithNoRedirect)' ./internal/connectors/sources/http`. +- **What the API answered is redacted before the model reads it** (AI-3674, S1.2). A tool error goes through the call's `core.Exchange.Redact` (`core.Observed`: the dispatcher's Exchange, or one of the call's own), which takes out the credential's strings and the request's path and query, before the 32 KiB cut, so a credential the cut falls in leaves no start of itself. A 2xx result goes through `core.Exchange.RedactCredential`, which takes out the credential's secret values only: its path and query stay, since an answer names its resource by them, and so does api_key's header name (`core.SecretValuer`). Check: `go test -run 'TestSourceSuite/TestA(ToolError(Echoing|IsRedacted)|2xxEchoing)|TestAcceptanceSuite/TestA(403|200)' ./internal/connectors/sources/http`. +- **No argument or credential on a log line.** The session's dispatcher logs `core.LoggedMessage` of the call's error with the Exchange's `Redact`: the URL a client error names is cut to its scheme and host, and a tool error is redacted. Check: `go test -run 'TestAcceptanceSuite/TestALogLine' ./internal/connectors/sources/http`. - **The endpoint and the path are joined as text.** Never `url.ResolveReference`, which drops the endpoint's own path for a path starting with `/`; `core.Manifest.Validate` refuses a path starting with `//` or holding `\`. Check: `go test -run 'TestSourceSuite/TestTheEndpointsOwnPath' ./internal/connectors/sources/http`. - **A tool is offered only when its grant names it and pins the digest it has now.** The digest covers method, path and read_only beside what the model is shown, so a revision that turns a POST into a read-only GET is a new digest, and a connection pinned to one revision never runs a tool under a grant made for the other (AI-3674, from the AI-3673 review). Check: `go test -run 'TestHTTPSourceContract/(TestOnlyTheGranted|TestAnUngranted|TestAToolWhoseSchema)|TestSourceSuite/(TestAGrantForAnotherRevision|TestTheDigestCovers)' ./internal/connectors/sources/http`. - **Arguments are checked before anything is sent**, against the schema built from the declared parameters (JSON Schema 2020-12). Check: `go test -run 'TestHTTPSourceContract/TestArguments' ./internal/connectors/sources/http`. @@ -47,8 +62,8 @@ Toolset.Call(call) - **Bounded.** One body is read up to 4 MiB (`maxResponseBytes`, the mcp source's cap); one result or tool error is at most `core.MaxResultBytes` (32 KiB), ending with `core.TruncatedMarker`. An opened toolset's client waits at least `callTimeout` (35 s), past the longest `timeout_ms` a binding may ask for (30 s), and `Binding.Timeout` bounds a call when set. Check: `go test -run 'TestHTTPSourceContract/TestAResultOverTheCap|TestSourceSuite/(TestABodyIsRead|TestAnOpenedToolsetWaits|TestTheBindingsTimeout)' ./internal/connectors/sources/http`. - **Every hardcoded value says where it comes from**, beside it: `Separator`, `defaultCallTimeout`, `maxResponseBytes`, `nonText`, `bodyMethods`. -Not here yet (AI-3675, call-time safety): refusing an undeclared argument before sending (today it is dropped), refusing a `.` or `..` path value, refusing an override name at `Open`, redirect rules beyond egress's, and redacting arguments from log lines. A manifest that sets `sources[].tools` (the `needs_scopes` rules) on an http source is refused (`checkHTTPSource`), as the source reads none: no tool is left out for a scope and validate reports none. +A grant reads only at its digest: `internal/api` judges an http tool read_only (`grantSendsOut`, for a config saved beside a sensitive connector and for a connection's tools listing) only when the grant, or the connection's listed tool, pins the latest revision's read-only digest, since a session opens a tool only at its pinned digest, which covers method and read_only (AI-3675, from AI-3674's Q1). A manifest that sets `sources[].tools` (the `needs_scopes` rules) on an http source is refused (`checkHTTPSource`), as the source reads none: no tool is left out for a scope and validate reports none. ## Tests -From `acceleration/`: `go test -race ./internal/connectors/sources/http`. `TestHTTPSourceContract` runs `core/contracttest.SourceContract`; `SourceSuite` the rest. The provider is a loopback TLS server that takes one bearer token, records each request and answers by path, reached through `core.Transports` with the `bearer` scheme. No mocks (`.claude/skills/go-testing/SKILL.md`). +From `acceleration/`: `go test -race ./internal/connectors/sources/http`. `TestHTTPSourceContract` runs `core/contracttest.SourceContract`; `SourceSuite` the rest. The provider is a loopback TLS server that takes one bearer token, records each request and answers by path, reached through `core.Transports` with the `bearer` scheme. `AcceptanceSuite` is AC-6 and AC-9 of AI-3669 against `fakeprovider`'s HTTP API, with the `api_key` scheme. No mocks (`.claude/skills/go-testing/SKILL.md`). diff --git a/acceleration/internal/connectors/sources/http/acceptance_test.go b/acceleration/internal/connectors/sources/http/acceptance_test.go new file mode 100644 index 0000000000..2c8318279a --- /dev/null +++ b/acceleration/internal/connectors/sources/http/acceptance_test.go @@ -0,0 +1,236 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/fakeprovider" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/apikey" + "github.com/GetStream/Vision-Agents/acceleration/internal/llm" +) + +// AcceptanceSuite is AC-6 and AC-9 of AI-3669 against the fake provider's HTTP API, with an +// api_key connection whose key the API takes. +type AcceptanceSuite struct { + suite.Suite + ctx context.Context + provider *fakeprovider.Server + source *Source +} + +func TestAcceptanceSuite(t *testing.T) { + suite.Run(t, new(AcceptanceSuite)) +} + +func (s *AcceptanceSuite) SetupTest() { + s.ctx = context.Background() + s.provider = fakeprovider.New(s.T()) + s.source = New() +} + +// AC-6 of AI-3669: a read-only GET called with _method=DELETE and X-HTTP-Method-Override=DELETE +// is refused before sending, and the provider records no request; with valid arguments it records +// exactly one GET with no override header, the path value ../admin escaped as one segment. +func (s *AcceptanceSuite) TestAnOverrideIsRefusedBeforeSendingAndAValidCallIsOneGET() { + tool := core.HTTPTool{Name: "get_item", Description: "Calls the API.", Method: http.MethodGet, Path: "/items/{id}", ReadOnly: true, + Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}}} + + _, err := s.call(tool, `{"id":"1","_method":"DELETE","X-HTTP-Method-Override":"DELETE"}`) + + s.EqualError(err, "http: crm__get_item: an argument is not one of the tool's parameters, so nothing was sent") + s.Empty(s.provider.APIRequests()) + + result, err := s.call(tool, `{"id":"../admin"}`) + + s.Require().NoError(err) + s.Equal("ok", llm.TextOf(result.Parts)) + requests := s.provider.APIRequests() + s.Require().Len(requests, 1) + s.Equal(http.MethodGet, requests[0].Method) + s.Equal(fakeprovider.PathAPI+"/items/..%2Fadmin", requests[0].URI) + for _, header := range []string{"X-HTTP-Method-Override", "X-Method-Override", "X-HTTP-Method"} { + s.Empty(requests[0].Header.Values(header), header) + } + s.Empty(requests[0].Body) +} + +// AC-9 of AI-3669: a 100 KiB answer reads as at most 32 KiB ending with the marker, and of a +// 5 MiB one only the first 4 MiB is read: past them the fake's bytes are not UTF-8, which would +// read as nonText. +func (s *AcceptanceSuite) TestAnAnswerIsReadUpTo4MiBAndReadAsAtMost32KiB() { + tool := core.HTTPTool{Name: "get_bytes", Description: "Calls the API.", Method: http.MethodGet, Path: "/bytes/{size}", ReadOnly: true, + Parameters: map[string]core.HTTPParameter{"size": {Type: "integer", Required: true}, "then": {Type: "integer"}}} + + for _, arguments := range []string{`{"size":102400}`, `{"size":4194304,"then":1048576}`} { + result, err := s.call(tool, arguments) + + s.Require().NoError(err, arguments) + text := llm.TextOf(result.Parts) + s.LessOrEqual(len(text), 32<<10, arguments) + s.True(strings.HasPrefix(text, "aaaa"), arguments) + s.True(strings.HasSuffix(text, core.TruncatedMarker), arguments) + } +} + +// S1.2 of AI-3674: an API answering 403 with the api_key and the Authorization it got does not +// put the key in the conversation. +func (s *AcceptanceSuite) TestA403EchoingTheKeyIsRedacted() { + _, err := s.call(core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/echo-credential"}, `{}`) + + var reported *core.ToolError + s.Require().ErrorAs(err, &reported) + s.Equal(`The API answered 403 Forbidden: {"error":"key [redacted] and may not read this"}`, reported.Message) + s.NotContains(reported.Message, s.provider.APIKey) +} + +// An API answering 200 with the api_key it got does not put the key in the conversation either; +// the rest of the answer stays as it came. +func (s *AcceptanceSuite) TestA200EchoingTheKeyIsRedacted() { + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/echo-credential", ReadOnly: true, + Parameters: map[string]core.HTTPParameter{"status": {Type: "string"}}} + + result, err := s.call(tool, `{"status":"200"}`) + + s.Require().NoError(err) + s.Equal(`{"error":"key [redacted] and may not read this"}`, llm.TextOf(result.Parts)) +} + +// R1.1 of AI-3675: a 2xx takes out api_key's key but keeps its header's name, which an API's +// answer may say, as its docs do; an error still takes out both, as Redact did before. +func (s *AcceptanceSuite) TestA2xxKeepsTheKeysHeaderName() { + api := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/rest/denied" { + w.WriteHeader(http.StatusForbidden) + } + _, _ = io.WriteString(w, `{"docs":"send `+fakeprovider.APIKeyHeader+`","seen":"`+r.Header.Get(fakeprovider.APIKeyHeader)+`"}`) + })) + defer api.Close() + transports, err := core.NewTransports(core.TransportsConfig{Resolver: keyResolver{key: "k3675-secret"}, + Timeout: requestTimeout, NewClient: loopback(api.Client())}) + s.Require().NoError(err) + + for path, want := range map[string]string{ + "/ok": `{"docs":"send X-Api-Key","seen":"[redacted]"}`, + "/denied": `The API answered 403 Forbidden: {"docs":"send [redacted]","seen":"[redacted]"}`, + } { + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: path} + binding := s.binding(tool) + binding.Manifest.Endpoints[Kind] = api.URL + fakeprovider.PathAPI + binding.HTTP = transports.Client(core.ConnectionRef{CustomerID: "app", ConnectionID: "crm-1"}, apikey.New()) + set, err := s.source.Open(s.ctx, binding, s.grants(binding, "get")) + s.Require().NoError(err) + + result, err := set.Call(s.ctx, llm.ToolCall{Name: "crm__get", Arguments: `{}`}) + + text := llm.TextOf(result.Parts) + var reported *core.ToolError + if errors.As(err, &reported) { + text = reported.Message + } else { + s.Require().NoError(err, path) + } + s.Equal(want, text, path) + } +} + +// The log line of a call (core.LoggedMessage, with the call's Exchange.Redact, as the session's +// dispatcher writes it) holds no argument value and no credential: the URL the client's error +// names is cut to its scheme and host, and the tool error is redacted. +func (s *AcceptanceSuite) TestALogLineHoldsNoArgumentAndNoCredential() { + lookup := core.HTTPTool{Name: "lookup", Description: "Calls the API.", Method: http.MethodGet, Path: "/people/{id}", + Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}, "email": {Type: "string"}}} + transports, err := core.NewTransports(core.TransportsConfig{Resolver: keyResolver{key: s.provider.APIKey}, Timeout: requestTimeout}) + s.Require().NoError(err) + unreached := s.binding(lookup) + unreached.Manifest.Endpoints[Kind] = "https://127.0.0.1:8443/rest" + unreached.HTTP = transports.Client(core.ConnectionRef{CustomerID: "app", ConnectionID: "crm-1"}, apikey.New()) + echoed := s.binding(core.HTTPTool{Name: "lookup", Description: "Calls the API.", Method: http.MethodGet, Path: "/echo-credential", + Parameters: map[string]core.HTTPParameter{"email": {Type: "string"}}}) + + for name, binding := range map[string]core.ResolvedBinding{"egress refuses the host": unreached, "the API echoes the key": echoed} { + arguments := `{"id":"u-3675","email":"alice@example.com"}` + if name == "the API echoes the key" { + arguments = `{"email":"alice@example.com"}` + } + set, err := s.source.Open(s.ctx, binding, s.grants(binding, "lookup")) + s.Require().NoError(err) + ctx, exchange := core.WithExchange(s.ctx) + + _, err = set.Call(ctx, llm.ToolCall{Name: "crm__lookup", Arguments: arguments}) + + s.Require().Error(err, name) + logged := core.LoggedMessage(err, exchange.Redact) + for _, secret := range []string{"alice", "example.com", "u-3675", "/people", s.provider.APIKey} { + s.NotContains(logged, secret, name) + } + } +} + +// call opens tool, granted at its digest, on an api_key connection to the fake's API and calls it. +func (s *AcceptanceSuite) call(tool core.HTTPTool, arguments string) (core.Result, error) { + binding := s.binding(tool) + set, err := s.source.Open(s.ctx, binding, s.grants(binding, tool.Name)) + s.Require().NoError(err) + s.Require().Len(set.Tools(), 1) + return set.Call(s.ctx, llm.ToolCall{Name: "crm" + Separator + tool.Name, Arguments: arguments}) +} + +func (s *AcceptanceSuite) grants(binding core.ResolvedBinding, name string) []core.ToolGrant { + specs, err := s.source.Discover(s.ctx, binding) + s.Require().NoError(err) + for _, spec := range specs { + if spec.Name == name { + return []core.ToolGrant{{Name: name, SchemaDigest: spec.SchemaDigest}} + } + } + s.FailNow("no such tool", name) + return nil +} + +// binding reaches the fake's API under the alias crm, through core.Transports with the api_key +// scheme and the key the API takes. +func (s *AcceptanceSuite) binding(tools ...core.HTTPTool) core.ResolvedBinding { + transports, err := core.NewTransports(core.TransportsConfig{Resolver: keyResolver{key: s.provider.APIKey}, + Timeout: requestTimeout, NewClient: loopback(s.provider.Client())}) + s.Require().NoError(err) + return core.ResolvedBinding{ + Binding: core.Binding{Name: "crm"}, + Manifest: core.ResolvedManifest{ConnectorID: "custom_crm", Scheme: apikey.Name, + Endpoints: map[string]string{Kind: s.provider.URL + fakeprovider.PathAPI}, + Sources: []core.SourceRule{{Kind: Kind, Endpoint: Kind, HTTPTools: tools}}}, + HTTP: transports.Client(core.ConnectionRef{CustomerID: "app", ConnectionID: "crm-1"}, apikey.New()), + } +} + +// keyResolver hands out key, sent in fakeprovider.APIKeyHeader, for every connection. +type keyResolver struct { + key string +} + +func (r keyResolver) Resolve(context.Context, core.ConnectionRef, core.CredentialRequest) (core.AccessCredential, error) { + secret, err := json.Marshal(map[string]string{"header": fakeprovider.APIKeyHeader, "key": r.key}) + if err != nil { + return core.AccessCredential{}, err + } + credential := core.NewAccessCredential(apikey.Name, time.Time{}, secret) + credential.Revision = 1 + return credential, nil +} + +func (keyResolver) Invalidate(context.Context, core.ConnectionRef, core.AccessCredential, core.Outcome) error { + return nil +} + +func (keyResolver) Revoke(context.Context, core.ConnectionRef, core.SignalKind, time.Time) error { + return nil +} diff --git a/acceleration/internal/connectors/sources/http/source.go b/acceleration/internal/connectors/sources/http/source.go index 548c5c527e..ffe2880c38 100644 --- a/acceleration/internal/connectors/sources/http/source.go +++ b/acceleration/internal/connectors/sources/http/source.go @@ -100,6 +100,12 @@ func (s *Source) Open(_ context.Context, b core.ResolvedBinding, grants []core.T if err != nil { return nil, err } + // Validation refused such a source when it was stored; it is refused again here, the last + // step before a request, so one that skipped it never names a method override or writes + // while saying it reads. + if err := core.CheckHTTPSource(*rule); err != nil { + return nil, stack.Wrap(fmt.Errorf("http: connector %q: %w", b.Manifest.ConnectorID, err)) + } granted := make(map[string]string, len(grants)) for _, grant := range grants { granted[grant.Name] = grant.SchemaDigest @@ -148,15 +154,47 @@ func ToolSchemaDigest(tool core.HTTPTool) (string, error) { } // callClient is the connection's client for an opened Toolset: the same client, with a timeout -// no shorter than callTimeout, so it never cuts a call before the caller's deadline. +// no shorter than callTimeout, so it never cuts a call before the caller's deadline, and which +// follows a redirect only for a GET or a HEAD (redirectMethods), within the client's own policy. func (s *Source) callClient(client *http.Client) *http.Client { copied := *client if copied.Timeout < s.callTimeout { copied.Timeout = s.callTimeout } + policy := client.CheckRedirect + copied.CheckRedirect = func(request *http.Request, via []*http.Request) error { + if !slices.Contains(redirectMethods, via[0].Method) { + return http.ErrUseLastResponse + } + if policy == nil { + return defaultRedirects(via) + } + return policy(request, via) + } return &copied } +// redirectMethods are the methods whose call follows a redirect: the reads. Any other method +// gets the redirect as its answer, which the model reads as a tool error naming its status, or, +// for a 301, a 302 or a 303, as a result saying the request may have run (Toolset.Call). A +// write's method and path are what the manifest fixes and its owner approved, and net/http sends +// a POST, a PUT or a PATCH body again on a 307 or a 308 (AI-3674 R1.6), so following one would run +// the write, and maybe write twice, at a path the manifest does not name. The egress client +// (core.Transports) already follows only within the origin and keeps the method. +var redirectMethods = []string{http.MethodGet, http.MethodHead} + +// maxRedirects is net/http's own limit, which a client with no CheckRedirect has +// (defaultCheckRedirect, net/http/client.go: "stopped after 10 redirects"). +const maxRedirects = 10 + +// defaultRedirects is net/http's redirect policy, for a client that sets none. +func defaultRedirects(via []*http.Request) error { + if len(via) >= maxRedirects { + return fmt.Errorf("http: stopped after %d redirects", maxRedirects) + } + return nil +} + // httpSource is the manifest's http source and the URL of its endpoint. func httpSource(b core.ResolvedBinding) (*core.SourceRule, string, error) { rule := core.HTTPSource(b.Manifest.Sources) diff --git a/acceleration/internal/connectors/sources/http/source_test.go b/acceleration/internal/connectors/sources/http/source_test.go index a0a579696c..9a30d030cb 100644 --- a/acceleration/internal/connectors/sources/http/source_test.go +++ b/acceleration/internal/connectors/sources/http/source_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "strconv" "strings" "sync" "testing" @@ -73,7 +74,7 @@ func (s *SourceSuite) SetupTest() { // parameters in the query, each as the model wrote it; one left out is not sent. The manifest's // headers and the connection's credential are on it. func (s *SourceSuite) TestAGETSendsItsPathParameterInThePathAndTheOthersInTheQuery() { - tool := core.HTTPTool{Name: "get_forecast", Method: http.MethodGet, Path: "/v1/forecast/{city}", ReadOnly: true, + tool := core.HTTPTool{Name: "get_forecast", Description: "Calls the API.", Method: http.MethodGet, Path: "/v1/forecast/{city}", ReadOnly: true, Parameters: map[string]core.HTTPParameter{ "city": {Type: "string", Required: true}, "latitude": {Type: "number", Required: true}, "current": {Type: "string"}, "days": {Type: "integer"}, "past": {Type: "boolean"}, "hourly": {Type: "boolean"}, @@ -98,7 +99,7 @@ func (s *SourceSuite) TestAGETSendsItsPathParameterInThePathAndTheOthersInTheQue // AC of AI-3674 and AC-8 of AI-3669: a POST sends its other parameters as a JSON object, numbers // as the model wrote them, so 2^53+1 is not rounded through a float. func (s *SourceSuite) TestAPOSTSendsItsOtherParametersAsAJSONBody() { - tool := core.HTTPTool{Name: "echo", Method: http.MethodPost, Path: "/items/{id}", + tool := core.HTTPTool{Name: "echo", Description: "Calls the API.", Method: http.MethodPost, Path: "/items/{id}", Parameters: map[string]core.HTTPParameter{ "id": {Type: "string", Required: true}, "message": {Type: "string", Required: true}, "count": {Type: "integer"}, "urgent": {Type: "boolean"}, @@ -133,7 +134,7 @@ func (s *SourceSuite) TestEachMethodSendsItsParametersWhereTheRuleSays() { {http.MethodPost, `{"id":"7"}`, url.Values{}, `{}`}, } { s.provider.reset() - tool := core.HTTPTool{Name: "act", Method: test.method, Path: "/items/{id}", + tool := core.HTTPTool{Name: "act", Description: "Calls the API.", Method: test.method, Path: "/items/{id}", Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}, "q": {Type: "string"}}} _, err := s.call(s.binding(tool), "act", test.arguments) @@ -147,21 +148,279 @@ func (s *SourceSuite) TestEachMethodSendsItsParametersWhereTheRuleSays() { } } -// Only what the tool declares is sent: an override the model adds goes nowhere (AC-6 of AI-3669, -// whose refusal before sending is AI-3675's). -func (s *SourceSuite) TestAnArgumentTheToolDoesNotDeclareIsNotSent() { - _, err := s.call(s.binding(echoTool()), contracttest.ToolEcho, - `{"text":"hi","_method":"DELETE","X-HTTP-Method-Override":"DELETE"}`) +// AC-6 of AI-3669: an argument the tool does not declare is refused before anything is sent, +// whatever it is named and whatever the method, with one sentence; the declared ones alone are +// sent. +func (s *SourceSuite) TestAnArgumentTheToolDoesNotDeclareIsRefusedBeforeSending() { + post := core.HTTPTool{Name: contracttest.ToolEcho, Description: "Calls the API.", Method: http.MethodPost, Path: "/echo", + Parameters: map[string]core.HTTPParameter{"text": {Type: "string", Required: true}}} + for _, tool := range []core.HTTPTool{echoTool(), post} { + for _, arguments := range []string{ + `{"text":"hi","_method":"DELETE"}`, + `{"text":"hi","X-HTTP-Method-Override":"DELETE"}`, + `{"text":"hi","x-http-method-override":"DELETE"}`, + `{"text":"hi","X-Method-Override":"DELETE","X-HTTP-Method":"DELETE"}`, + `{"text":"hi","Text":"hi"}`, + `{"text":"hi","extra":null}`, + `{"text":"hi","nested":{"_method":"DELETE"}}`, + } { + s.provider.reset() + + _, err := s.call(s.binding(tool), contracttest.ToolEcho, arguments) + + s.EqualError(err, "http: crm__echo: an argument is not one of the tool's parameters, so nothing was sent", + tool.Method+" "+arguments) + s.Empty(s.provider.requests(), tool.Method+" "+arguments) + } + } + + _, err := s.call(s.binding(echoTool()), contracttest.ToolEcho, `{"text":"hi"}`) s.Require().NoError(err) sent := s.only() s.Equal(http.MethodGet, sent.method) s.Equal(url.Values{"text": {"hi"}}, sent.query) - s.Empty(sent.header.Get("X-HTTP-Method-Override")) +} + +// S1.3 of AI-3674: a segment of the path as built that holds a {name} and is empty, . or .. names +// another resource, so it is refused before anything is sent: the empty id that names the +// collection, and the .. that {a}{b} makes of . and .. A value with a / stays one segment, as AC-6 +// of AI-3669 says ../admin does, and a value escaped already keeps its %, so neither is a dot +// segment. +func (s *SourceSuite) TestAPathValueThatNamesAnotherResourceIsRefusedBeforeSending() { + one := core.HTTPTool{Name: "remove", Description: "Calls the API.", Method: http.MethodDelete, Path: "/items/{id}", + Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}}} + inner := core.HTTPTool{Name: "remove", Description: "Calls the API.", Method: http.MethodDelete, Path: "/items/{id}/notes", + Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}}} + pair := core.HTTPTool{Name: "remove", Description: "Calls the API.", Method: http.MethodDelete, Path: "/items/{a}{b}", + Parameters: map[string]core.HTTPParameter{"a": {Type: "string", Required: true}, "b": {Type: "string", Required: true}}} + number := core.HTTPTool{Name: "remove", Description: "Calls the API.", Method: http.MethodDelete, Path: "/items/{id}", + Parameters: map[string]core.HTTPParameter{"id": {Type: "integer", Required: true}}} + + for _, test := range []struct { + tool core.HTTPTool + arguments string + // path is what the provider receives, "" when the call is refused. + path string + }{ + {one, `{"id":""}`, ""}, + {one, `{"id":"."}`, ""}, + {one, `{"id":".."}`, ""}, + {inner, `{"id":""}`, ""}, + {inner, `{"id":".."}`, ""}, + {pair, `{"a":".","b":"."}`, ""}, + {pair, `{"a":"","b":""}`, ""}, + {pair, `{"a":".","b":""}`, ""}, + {pair, `{"a":"","b":".."}`, ""}, + {one, `{"id":"../admin"}`, "/api/items/..%2Fadmin"}, + {one, `{"id":"..%2F"}`, "/api/items/..%252F"}, + {one, `{"id":"%2e%2e"}`, "/api/items/%252e%252e"}, + {one, `{"id":"..."}`, "/api/items/..."}, + {one, `{"id":" "}`, "/api/items/%20"}, + {inner, `{"id":"7"}`, "/api/items/7/notes"}, + {pair, `{"a":".","b":"x"}`, "/api/items/.x"}, + {pair, `{"a":"","b":"."}`, ""}, + {number, `{"id":0}`, "/api/items/0"}, + } { + s.provider.reset() + + _, err := s.call(s.binding(test.tool), "remove", test.arguments) + + if test.path == "" { + s.EqualError(err, "http: crm__remove: a path parameter is empty, . or .., which names another resource "+ + "than the tool's, so nothing was sent", test.tool.Path+" "+test.arguments) + s.Empty(s.provider.requests(), test.tool.Path+" "+test.arguments) + continue + } + s.Require().NoError(err, test.tool.Path+" "+test.arguments) + s.Equal(test.path, s.only().path, test.tool.Path+" "+test.arguments) + } +} + +// AI-3673 refuses a manifest whose tool names a method override, or writes while saying it +// reads, when it is stored; Open refuses one again, so a stored manifest that skipped validation +// offers no tool and sends nothing. +func (s *SourceSuite) TestOpenRefusesASourceThatBreaksARuleOfValidation() { + for name, change := range map[string]func(*core.SourceRule){ + "a parameter _method": func(r *core.SourceRule) { + r.HTTPTools[0].Parameters["_method"] = core.HTTPParameter{Type: "string"} + }, + "a parameter X-HTTP-Method-Override": func(r *core.SourceRule) { + r.HTTPTools[0].Parameters["X-HTTP-Method-Override"] = core.HTTPParameter{Type: "string"} + }, + "a header x-method-override": func(r *core.SourceRule) { r.Headers["x-method-override"] = "DELETE" }, + "a header X-HTTP-Method": func(r *core.SourceRule) { r.Headers["X-HTTP-Method"] = "DELETE" }, + "a read-only POST": func(r *core.SourceRule) { r.HTTPTools[0].Method = http.MethodPost }, + "a read-only DELETE": func(r *core.SourceRule) { r.HTTPTools[0].Method = http.MethodDelete }, + } { + tool := echoTool() + tool.ReadOnly = true + binding := s.binding(tool) + grants := s.grants(binding, contracttest.ToolEcho) + change(&binding.Manifest.Sources[0]) + + set, err := s.source.Open(s.ctx, binding, grants) + + s.ErrorContains(err, `http: connector "custom_crm": sources[http]`, name) + s.Nil(set, name) + } + s.Empty(s.provider.requests()) + tool := echoTool() + tool.ReadOnly = true + _, err := s.call(s.binding(tool), contracttest.ToolEcho, `{"text":"hi"}`) + s.Require().NoError(err, "the same source unchanged opens") +} + +// R1.6 of AI-3674: a write's redirect is its answer, so a 307 or a 308 never sends its body +// again, nor a DELETE to another path; a GET or a HEAD follows one within the origin. R1.2 of +// AI-3675: a write answered 301, 302 or 303 may have run, so the model reads that as a result. +func (s *SourceSuite) TestOnlyAReadFollowsARedirect() { + for _, test := range []struct { + method, path string + // err is the tool error the model reads, and answer the result, both "" when the + // redirect is followed. + err, answer string + }{ + {http.MethodPost, "/moved-307", "The API answered 307 Temporary Redirect", ""}, + {http.MethodPost, "/moved-308", "The API answered 308 Permanent Redirect", ""}, + {http.MethodPut, "/moved-307", "The API answered 307 Temporary Redirect", ""}, + {http.MethodPatch, "/moved-308", "The API answered 308 Permanent Redirect", ""}, + {http.MethodDelete, "/moved-307", "The API answered 307 Temporary Redirect", ""}, + {http.MethodPost, "/moved-303", "", "The API answered 303 See Other; the request may have run."}, + {http.MethodPut, "/moved-301", "", "The API answered 301 Moved Permanently; the request may have run."}, + {http.MethodPatch, "/moved-302", "", "The API answered 302 Found; the request may have run."}, + {http.MethodDelete, "/moved-303", "", "The API answered 303 See Other; the request may have run."}, + {http.MethodPost, "/moved-reason", "", "The API answered 303 See Other; the request may have run."}, + {http.MethodGet, "/moved-307", "", ""}, + {http.MethodGet, "/moved-301", "", ""}, + {http.MethodGet, "/moved-302", "", ""}, + {http.MethodGet, "/moved-303", "", ""}, + {http.MethodHead, "/moved-308", "", ""}, + {http.MethodHead, "/moved-303", "", ""}, + // A 3xx with no Location is not followed (net/http): a read's is a tool error, as before. + {http.MethodGet, "/moved-nowhere", "The API answered 302 Found", ""}, + } { + s.provider.reset() + tool := core.HTTPTool{Name: "act", Description: "Calls the API.", Method: test.method, Path: test.path, + Parameters: map[string]core.HTTPParameter{"q": {Type: "string"}}} + + result, err := s.call(s.binding(tool), "act", `{"q":"x"}`) + + received := s.provider.requests() + if test.answer != "" { + s.Require().NoError(err, test.method+" "+test.path) + s.Equal(test.answer, llm.TextOf(result.Parts), test.method+" "+test.path) + s.Len(received, 1, test.method+" "+test.path+": the target got nothing") + continue + } + if test.err == "" { + s.Require().NoError(err, test.method+" "+test.path) + s.Require().Len(received, 2, test.method+" "+test.path) + s.Equal("/api/target", received[1].path, test.method+" "+test.path) + s.Equal(test.method, received[1].method, test.method+" "+test.path) + continue + } + var reported *core.ToolError + s.Require().ErrorAs(err, &reported, test.method+" "+test.path) + s.Equal(test.err, reported.Message, test.method+" "+test.path) + s.Len(received, 1, test.method+" "+test.path+": the target got nothing") + } +} + +// A redirect to another origin is never followed, so the credential never reaches it: the +// egress client's policy, which the toolset's client keeps for a GET. +func (s *SourceSuite) TestARedirectToAnotherOriginNeverCarriesTheCredential() { + var reached []string + other := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reached = append(reached, r.Header.Get("Authorization")) + })) + defer other.Close() + first := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, other.URL+"/steal", http.StatusTemporaryRedirect) + })) + defer first.Close() + transports, err := core.NewTransports(core.TransportsConfig{Resolver: tokenResolver{}, Timeout: requestTimeout, + NewClient: loopback(first.Client())}) + s.Require().NoError(err) + binding := s.binding(echoTool()) + binding.Manifest.Endpoints[Kind] = first.URL + "/api" + binding.HTTP = transports.Client(core.ConnectionRef{CustomerID: "app", ConnectionID: "crm-1"}, bearer.New()) + + _, err = s.call(binding, contracttest.ToolEcho, `{"text":"hi"}`) + + s.Contains(core.LoggedMessage(err, nil), "egress: redirect to another host refused") + s.Empty(reached, "the other origin got no request at all") +} + +// A client with no redirect policy of its own stops a read's redirects where net/http does. +func (s *SourceSuite) TestAClientWithNoRedirectPolicyStopsAfterTenRedirects() { + binding := s.binding(core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/loop"}) + binding.HTTP.CheckRedirect = nil + + _, err := s.call(binding, "get", `{}`) + + s.Contains(core.LoggedMessage(err, nil), "stopped after 10 redirects") + s.Len(s.provider.requests(), 10, "the first request and the nine redirects before the tenth, which is not followed") +} + +// S1.2 of AI-3674: an API that echoes the request's credential in its error does not put it in +// the conversation: the tool error is redacted with the call's Exchange, as the log line is, +// before it is cut, so a credential the cut falls in leaves no start of itself either. +func (s *SourceSuite) TestAToolErrorEchoingTheCredentialIsRedacted() { + for path, want := range map[string]string{ + "/echo-credential": `The API answered 403 Forbidden: {"error":"key Bearer [redacted] may not read this"}`, + "/echo-at-the-cut": "", + } { + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: path} + set, err := s.source.Open(s.ctx, s.binding(tool), s.grants(s.binding(tool), "get")) + s.Require().NoError(err) + ctx, exchange := core.WithExchange(s.ctx) + + _, err = set.Call(ctx, llm.ToolCall{Name: "crm__get", Arguments: `{}`}) + + var reported *core.ToolError + s.Require().ErrorAs(err, &reported, path) + s.NotContains(reported.Message, "tok", path) + s.NotContains(core.LoggedMessage(err, exchange.Redact), "tok", path) + s.Equal(http.StatusForbidden, exchange.Status(), "the caller's Exchange saw the answer: %s", path) + if want != "" { + s.Equal(want, reported.Message, path) + continue + } + s.True(strings.HasSuffix(reported.Message, "Bearer [re"+core.TruncatedMarker), path) + } +} + +// An API that echoes the request's credential in a 2xx does not put it in the conversation +// either, with or without an Exchange of the caller's; the path and query it names are kept. +func (s *SourceSuite) TestA2xxEchoingTheCredentialIsRedactedAndKeepsItsPath() { + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/echo-credential-ok/{id}", ReadOnly: true, + Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}, "q": {Type: "string"}}} + for name, ctx := range map[string]context.Context{"the caller's Exchange": func() context.Context { + ctx, _ := core.WithExchange(s.ctx) + return ctx + }(), "no Exchange": s.ctx} { + set, err := s.source.Open(s.ctx, s.binding(tool), s.grants(s.binding(tool), "get")) + s.Require().NoError(err) + + result, err := set.Call(ctx, llm.ToolCall{Name: "crm__get", Arguments: `{"id":"item-7","q":"open"}`}) + + s.Require().NoError(err, name) + s.Equal(`{"self":"/api/echo-credential-ok/item-7?q=open","seen":"Bearer [redacted]"}`, llm.TextOf(result.Parts), name) + } +} + +// A call without an Exchange of its caller's is redacted all the same, with one of its own. +func (s *SourceSuite) TestAToolErrorIsRedactedWithNoExchangeOfTheCallers() { + _, err := s.call(s.binding(core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/echo-credential"}), "get", `{}`) + + var reported *core.ToolError + s.Require().ErrorAs(err, &reported) + s.Equal(`The API answered 403 Forbidden: {"error":"key Bearer [redacted] may not read this"}`, reported.Message) } func (s *SourceSuite) TestNoArgumentsAtAllAreAnEmptyObject() { - tool := core.HTTPTool{Name: "list", Method: http.MethodGet, Path: "/items"} + tool := core.HTTPTool{Name: "list", Description: "Calls the API.", Method: http.MethodGet, Path: "/items"} result, err := s.call(s.binding(tool), "list", " ") @@ -189,8 +448,10 @@ func (s *SourceSuite) TestAnAnswerThatIsNotA2xxIsAToolErrorNamingItsStatus() { "/missing": "The API answered 404 Not Found: no such item", "/multiple-choices": "The API answered 300 Multiple Choices", "/refused": "The API answered 401 Unauthorized: bad token", + "/reason-own": "The API answered 403 Forbidden", + "/reason-unknown": "The API answered 499", } { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: path} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: path} _, err := s.call(s.binding(tool), "get", `{}`) @@ -198,7 +459,7 @@ func (s *SourceSuite) TestAnAnswerThatIsNotA2xxIsAToolErrorNamingItsStatus() { s.Require().ErrorAs(err, &reported, path) s.Equal(want, reported.Message, path) } - result, err := s.call(s.binding(core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/last-2xx"}), "get", `{}`) + result, err := s.call(s.binding(core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/last-2xx"}), "get", `{}`) s.Require().NoError(err, "299 is the last 2xx") s.Equal("ok", llm.TextOf(result.Parts)) } @@ -207,8 +468,10 @@ func (s *SourceSuite) TestAnAnswerThatIsNotA2xxIsAToolErrorNamingItsStatus() { // the model can tell done from nothing. func (s *SourceSuite) TestAnEmpty2xxIsItsStatus() { for want, tool := range map[string]core.HTTPTool{ - "The API answered 204 No Content.": {Name: "remove", Method: http.MethodDelete, Path: "/no-content"}, - "The API answered 200 OK.": {Name: "check", Method: http.MethodHead, Path: "/items"}, + "The API answered 204 No Content.": {Name: "remove", Description: "Calls the API.", Method: http.MethodDelete, Path: "/no-content"}, + "The API answered 200 OK.": {Name: "check", Description: "Calls the API.", Method: http.MethodHead, Path: "/items"}, + // S1.1 of AI-3675: the API's own reason phrase, here echoing the token, is not read. + "The API answered 202 Accepted.": {Name: "seen", Description: "Calls the API.", Method: http.MethodGet, Path: "/reason-echo"}, } { result, err := s.call(s.binding(tool), tool.Name, `{}`) @@ -218,7 +481,7 @@ func (s *SourceSuite) TestAnEmpty2xxIsItsStatus() { } func (s *SourceSuite) TestAToolErrorOverTheCapIsCutWithTheMarker() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/error-large"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/error-large"} _, err := s.call(s.binding(tool), "get", `{}`) @@ -229,7 +492,7 @@ func (s *SourceSuite) TestAToolErrorOverTheCapIsCutWithTheMarker() { } func (s *SourceSuite) TestABodyThatIsNotTextReadsAsNotText() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/binary"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/binary"} result, err := s.call(s.binding(tool), "get", `{}`) @@ -240,7 +503,7 @@ func (s *SourceSuite) TestABodyThatIsNotTextReadsAsNotText() { // The provider answers 4 MiB of text and then a byte that is not UTF-8: read past the cap, the // body would be no text at all. func (s *SourceSuite) TestABodyIsReadOnlyUpToTheCap() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/huge"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/huge"} result, err := s.call(s.binding(tool), "get", `{}`) @@ -252,7 +515,7 @@ func (s *SourceSuite) TestABodyIsReadOnlyUpToTheCap() { // R1.2: valid text whose cut at the cap falls inside a rune is still text, cut before that rune. func (s *SourceSuite) TestTextTheCapCutsInsideARuneIsStillText() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/huge-runes"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/huge-runes"} result, err := s.call(s.binding(tool), "get", `{}`) @@ -265,7 +528,7 @@ func (s *SourceSuite) TestTextTheCapCutsInsideARuneIsStillText() { // R1.3: the last byte under the 4 MiB cap is read: a body whose last byte there is not UTF-8 is // not text, under a cap even one byte lower too. func (s *SourceSuite) TestTheLastByteUnderTheCapIsRead() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/bad-byte-at-the-cap"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/bad-byte-at-the-cap"} result, err := s.call(s.binding(tool), "get", `{}`) @@ -275,7 +538,7 @@ func (s *SourceSuite) TestTheLastByteUnderTheCapIsRead() { // R1.3: a 4xx or a 5xx whose body is not text names its status and says so, never the bytes. func (s *SourceSuite) TestAToolErrorWithABodyThatIsNotTextSaysItIsNotText() { - _, err := s.call(s.binding(core.HTTPTool{Name: "broken", Method: http.MethodGet, Path: "/broken"}), "broken", `{}`) + _, err := s.call(s.binding(core.HTTPTool{Name: "broken", Description: "Calls the API.", Method: http.MethodGet, Path: "/broken"}), "broken", `{}`) var reported *core.ToolError s.Require().ErrorAs(err, &reported) @@ -286,8 +549,8 @@ func (s *SourceSuite) TestAToolErrorWithABodyThatIsNotTextSaysItIsNotText() { // made for one revision's x never opens the other's, so a connection still pinned to revision 1 // never runs the POST under a grant made for the read-only GET, nor the reverse. func (s *SourceSuite) TestAGrantForAnotherRevisionOfAToolIsNeverOpened() { - post := core.HTTPTool{Name: "x", Method: http.MethodPost, Path: "/x"} - get := core.HTTPTool{Name: "x", Method: http.MethodGet, Path: "/x", ReadOnly: true} + post := core.HTTPTool{Name: "x", Description: "Calls the API.", Method: http.MethodPost, Path: "/x"} + get := core.HTTPTool{Name: "x", Description: "Calls the API.", Method: http.MethodGet, Path: "/x", ReadOnly: true} revision1, revision2 := s.binding(post), s.binding(get) granted1, granted2 := s.grants(revision1, "x"), s.grants(revision2, "x") @@ -356,7 +619,7 @@ func (s *SourceSuite) TestTheInputSchemaIsTheDeclaredParameters() { Path: "/v1/forecast/{city}", Parameters: map[string]core.HTTPParameter{ "days": {Type: "integer", Description: "How many days."}, "city": {Type: "string", Required: true}, "at": {Type: "number", Required: true}}} - list := core.HTTPTool{Name: "list", Method: http.MethodGet, Path: "/items", + list := core.HTTPTool{Name: "list", Description: "Calls the API.", Method: http.MethodGet, Path: "/items", Parameters: map[string]core.HTTPParameter{"q": {Type: "string"}}} binding := s.binding(forecast, list) @@ -417,7 +680,7 @@ func (s *SourceSuite) TestAManifestWithNoHTTPSourceOrNoEndpointIsRefused() { // The connection's client cuts a request at its own timeout, which validate's requests keep; an // opened toolset's copy waits at least callTimeout, so the caller's deadline ends a call first. func (s *SourceSuite) TestAnOpenedToolsetWaitsPastTheConnectionsClientTimeout() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/slow"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/slow"} binding := s.provider.binding(s.T(), shortTimeout, tool) result, err := s.call(binding, "get", `{}`) @@ -442,7 +705,7 @@ func (s *SourceSuite) TestAClientWaitingLongerThanCallTimeoutKeepsItsTimeout() { } func (s *SourceSuite) TestABodyCutShortIsAnErrorNotAnAnswer() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/cut"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/cut"} _, err := s.call(s.binding(tool), "get", `{}`) @@ -457,7 +720,7 @@ func (s *SourceSuite) TestABodyCutShortIsAnErrorNotAnAnswer() { // one sentence, with no URL, no argument and nothing of the policy or the resolver; the log line // keeps why (core.LoggedMessage). func (s *SourceSuite) TestACallThatReachesNoAPIReadsOneSentence() { - lookup := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/people/{id}", + lookup := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/people/{id}", Parameters: map[string]core.HTTPParameter{"id": {Type: "string", Required: true}, "email": {Type: "string"}}} transports, err := core.NewTransports(core.TransportsConfig{Resolver: tokenResolver{}, Timeout: requestTimeout}) s.Require().NoError(err) @@ -478,7 +741,7 @@ func (s *SourceSuite) TestACallThatReachesNoAPIReadsOneSentence() { const unreachedSentence = "http: crm__get: the API could not be reached, or its answer did not arrive whole" func (s *SourceSuite) TestTheBindingsTimeoutBoundsACall() { - tool := core.HTTPTool{Name: "get", Method: http.MethodGet, Path: "/slow"} + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", Method: http.MethodGet, Path: "/slow"} binding := s.binding(tool) binding.Binding.Timeout = shortTimeout @@ -596,8 +859,37 @@ func (p *provider) serve(w http.ResponseWriter, r *http.Request) { case "/bad-byte-at-the-cap": _, _ = io.WriteString(w, strings.Repeat("a", 4<<20-1)) _, _ = w.Write([]byte{0xff}) + case "/moved-301", "/moved-302", "/moved-303", "/moved-307", "/moved-308": + code, _ := strconv.Atoi(strings.TrimPrefix(r.URL.Path, "/api/moved-")) + http.Redirect(w, r, "/api/target", code) + case "/moved-reason": + answerWithReason(w, "303 seen "+r.Header.Get("Authorization")) + case "/moved-nowhere": + w.WriteHeader(http.StatusFound) + case "/target": + _, _ = io.WriteString(w, "moved here") + case "/loop": + http.Redirect(w, r, "/api/loop", http.StatusTemporaryRedirect) + case "/echo-credential": + w.WriteHeader(http.StatusForbidden) + _, _ = io.WriteString(w, `{"error":"key `+r.Header.Get("Authorization")+` may not read this"}`) + case "/echo-credential-ok/item-7": + _, _ = io.WriteString(w, `{"self":"`+r.URL.RequestURI()+`","seen":"`+r.Header.Get("Authorization")+`"}`) + case "/echo-at-the-cut": + // The token starts 3 bytes before where core.CutResult cuts the tool error, "The API + // answered 403 Forbidden: " and this body: a cut made before redacting would keep "tok". + w.WriteHeader(http.StatusForbidden) + kept := core.MaxResultBytes - len(core.TruncatedMarker) + _, _ = io.WriteString(w, strings.Repeat("x", kept-3-len("The API answered 403 Forbidden: Bearer "))+ + r.Header.Get("Authorization")+strings.Repeat("y", 2*len(core.TruncatedMarker))) case "/no-content": w.WriteHeader(http.StatusNoContent) + case "/reason-echo": + answerWithReason(w, "202 seen "+r.Header.Get("Authorization")) + case "/reason-own": + answerWithReason(w, "403 Go away") + case "/reason-unknown": + answerWithReason(w, "499 Client Closed Request") case "/missing": w.WriteHeader(http.StatusNotFound) _, _ = io.WriteString(w, "no such item") @@ -627,6 +919,19 @@ func (p *provider) serve(w http.ResponseWriter, r *http.Request) { } } +// answerWithReason answers with an empty body and the status line "HTTP/1.1 ", status +// being a code and a reason phrase of the server's own, which net/http's ResponseWriter never +// writes. +func answerWithReason(w http.ResponseWriter, status string) { + conn, buffered, err := w.(http.Hijacker).Hijack() + if err != nil { + return + } + defer conn.Close() + _, _ = io.WriteString(buffered, "HTTP/1.1 "+status+"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + _ = buffered.Flush() +} + // binding reaches the provider's /api under the alias crm, through core.Transports with the // bearer scheme and a client that cuts a request at timeout, with tools as its http source's. func (p *provider) binding(t *testing.T, timeout time.Duration, tools ...core.HTTPTool) core.ResolvedBinding { diff --git a/acceleration/internal/connectors/sources/http/toolset.go b/acceleration/internal/connectors/sources/http/toolset.go index c7fba56c78..7be298f48e 100644 --- a/acceleration/internal/connectors/sources/http/toolset.go +++ b/acceleration/internal/connectors/sources/http/toolset.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "maps" @@ -41,6 +42,18 @@ var placeholder = regexp.MustCompile(`\{([^{}]*)\}`) // GET, HEAD and DELETE go in the query. var bodyMethods = []string{http.MethodPost, http.MethodPut, http.MethodPatch} +// The sentences the model reads of a call refused before anything was sent, each with the +// tool's name, so it can call again with what the tool takes. +const ( + // undeclaredArgument is an argument the tool does not declare, such as an _method or an + // X-HTTP-Method-Override the model adds (AC-6 of AI-3669): it is refused, not dropped, so + // the model does not take a call that went without it for one that went with it. + undeclaredArgument = "http: %s: an argument is not one of the tool's parameters, so nothing was sent" + // otherResource is a path value that would make the path name another resource (builtPath). + otherResource = "http: %s: a path parameter is empty, . or .., which names another resource than the tool's, " + + "so nothing was sent" +) + // Toolset is the granted tools of one http source, opened for one session. It is safe for // concurrent use: its tools are fixed when Open returns, and each call is its own request. type Toolset struct { @@ -74,10 +87,11 @@ func (*Toolset) Instructions() string { return "" } -// Call runs one offered tool: one request, whose answer the model reads as text. A name this -// toolset did not offer, or arguments its input schema refuses, never reach the API. An answer -// that is not a 2xx is a *core.ToolError naming its status, and an empty 2xx is its status. A -// result past core.MaxResultBytes is cut and ends with core.TruncatedMarker. +// Call runs one offered tool: one request, whose answer the model reads as text, with the +// connection's credential taken out of it. A name this toolset did not offer, or arguments its +// input schema refuses, never reach the API. An answer that is not a 2xx is a *core.ToolError +// naming its status, and an empty 2xx is its status. A result past core.MaxResultBytes is cut +// and ends with core.TruncatedMarker. func (t *Toolset) Call(ctx context.Context, call llm.ToolCall) (core.Result, error) { offered, found := t.targets[call.Name] if !found { @@ -92,9 +106,19 @@ func (t *Toolset) Call(ctx context.Context, call llm.ToolCall) (core.Result, err if err != nil { return core.Result{}, stack.Wrap(fmt.Errorf("http: %s: the arguments are not JSON: %w", call.Name, err)) } + if fields, ok := arguments.(map[string]any); ok { + for name := range fields { + if _, declared := offered.tool.Parameters[name]; !declared { + return core.Result{}, stack.Wrap(fmt.Errorf(undeclaredArgument, call.Name)) + } + } + } if err := offered.validator.Validate(arguments); err != nil { return core.Result{}, stack.Wrap(fmt.Errorf("http: %s: the arguments do not match the tool's input schema", call.Name)) } + // The call's Exchange, the dispatcher's, or one of its own for any other caller: what the + // API answered is redacted with it before the model reads it. + ctx, exchange := core.Observed(ctx) if t.timeout > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, t.timeout) @@ -102,6 +126,9 @@ func (t *Toolset) Call(ctx context.Context, call llm.ToolCall) (core.Result, err } // The schema takes only an object, so arguments is one. request, err := t.request(ctx, offered.tool, arguments.(map[string]any)) + if errors.Is(err, errOtherResource) { + return core.Result{}, stack.Wrap(fmt.Errorf(otherResource, call.Name)) + } if err != nil { return core.Result{}, err } @@ -121,21 +148,45 @@ func (t *Toolset) Call(ctx context.Context, call llm.ToolCall) (core.Result, err if utf8.ValidString(body) { text = body } + // A write answered 301, 302 or 303 may have run: a 303 points at its outcome, and a 301 or a + // 302 may be followed as a GET (RFC 9110 sections 15.4.2 to 15.4.4); only a 307 or a 308 asks + // for the same request again. So the model reads it as a result, not as an error it might + // answer by calling the write again (AI-3675 R1.2). A read follows it (callClient). + if slices.Contains(ranRedirects, response.StatusCode) && !slices.Contains(redirectMethods, offered.tool.Method) { + return core.Result{Parts: llm.TextParts("The API answered " + status(response) + "; the request may have run.")}, nil + } if response.StatusCode < 200 || response.StatusCode > 299 { - message := fmt.Sprintf("The API answered %s", response.Status) + message := "The API answered " + status(response) if len(body) > 0 { message += ": " + text } - return core.Result{}, stack.Wrap(&core.ToolError{Message: core.CutResult(message)}) + // An API may echo the request's credential or path in its error (AI-3674, S1.2): they + // are taken out before the cut, which could leave the start of one. + return core.Result{}, stack.Wrap(&core.ToolError{Message: core.CutResult(exchange.Redact(message))}) } // An empty answer, such as a 204's or any HEAD's, is its status, so the model can tell a // call that was done from one that said nothing. if len(body) == 0 { - return core.Result{Parts: llm.TextParts(fmt.Sprintf("The API answered %s.", response.Status))}, nil + return core.Result{Parts: llm.TextParts("The API answered " + status(response) + ".")}, nil } - return core.Result{Parts: llm.TextParts(core.CutResult(text))}, nil + // An API may echo the credential in an answer too, which the model reads as one: it is + // taken out, but the path and query, which an answer names its resource by, are kept. + return core.Result{Parts: llm.TextParts(core.CutResult(exchange.RedactCredential(text)))}, nil +} + +// status is the answer's code and net/http's text for it, such as "204 No Content": never the +// reason phrase the API sent, which is its own text and may echo the request's credential +// (AI-3675 S1.1). A code net/http has no text for is the code alone. +func status(response *http.Response) string { + return strings.TrimSpace(fmt.Sprintf("%d %s", response.StatusCode, http.StatusText(response.StatusCode))) } +// ranRedirects are the redirects a write may have run before (Call). +var ranRedirects = []int{http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther} + +// errOtherResource is a path value that would make the path name another resource (builtPath). +var errOtherResource = errors.New("a path value names another resource") + // unreached is a call to name that got no whole answer, for cause: one sentence for every such // failure, so the model reads no URL, no argument and nothing of the egress policy // (core.UnreachedError). @@ -147,17 +198,15 @@ func unreached(name string, cause error) error { func (*Toolset) Close() {} // request is the tool's request with arguments (AI-3669, «Decided»): each {name} in the path is -// its argument, escaped as one segment; the other parameters go in the query of a GET, a HEAD or +// its argument, escaped as one segment (builtPath); the other parameters go in the query of a GET, a HEAD or // a DELETE, and in a JSON object, the body, of a POST, a PUT or a PATCH. Only the parameters the // tool declares are sent. The URL is the endpoint and the path joined as text, never resolved as // a reference, which would drop the endpoint's own path. func (t *Toolset) request(ctx context.Context, tool core.HTTPTool, arguments map[string]any) (*http.Request, error) { - inPath := map[string]bool{} - path := placeholder.ReplaceAllStringFunc(tool.Path, func(match string) string { - name := match[1 : len(match)-1] - inPath[name] = true - return url.PathEscape(fmt.Sprint(arguments[name])) - }) + path, inPath, err := builtPath(tool.Path, arguments) + if err != nil { + return nil, err + } query := url.Values{} fields := map[string]any{} for _, name := range slices.Sorted(maps.Keys(tool.Parameters)) { @@ -195,6 +244,33 @@ func (t *Toolset) request(ctx context.Context, tool core.HTTPTool, arguments map return request, nil } +// builtPath is template with each {name} its argument, escaped as one segment, and the names +// it took, or errOtherResource when a segment that holds a {name} comes out empty, . or ..: an +// empty one names the collection (DELETE /items/ for an empty id, AI-3674 S1.3), and a dot +// segment its parent, which a client or a server resolves away (RFC 3986 section 5.2.4), so the +// request would reach a resource the tool's path does not name. Each segment is judged as it is +// built, so {a}{b} with . and . is refused as the .. it makes. A value holding a / stays one +// segment, the / sent as %2F (AC-6 of AI-3669: ../admin is ..%2Fadmin), and an escaped one stays +// as the model wrote it, its % sent as %25 (..%2F is ..%252F): neither is a dot segment. +func builtPath(template string, arguments map[string]any) (string, map[string]bool, error) { + inPath := map[string]bool{} + segments := strings.Split(template, "/") + for i, segment := range segments { + if !placeholder.MatchString(segment) { + continue + } + segments[i] = placeholder.ReplaceAllStringFunc(segment, func(match string) string { + name := match[1 : len(match)-1] + inPath[name] = true + return url.PathEscape(fmt.Sprint(arguments[name])) + }) + if segments[i] == "" || segments[i] == "." || segments[i] == ".." { + return "", nil, errOtherResource + } + } + return strings.Join(segments, "/"), inPath, nil +} + // offered is a tool as the model is shown it. func offered(name, description string, schema map[string]any) llm.Tool { return llm.Tool{Name: name, Description: description, Parameters: schema} diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 24c2953d73..9016acbcf6 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -2420,7 +2420,7 @@ func (s *DataMoveSuite) TestAnImportedDefinitionWhoseServerIsNotHTTPSIsRefused() // read-only GET tool on an API taking a key. const customWeather = `{"id": "custom_acme", "revision": 1, "name": "Weather", "endpoints": {"http": "https://api.weather.example/v1"}, "schemes": ["api_key"], "sources": [{"kind": "http", "endpoint": "http", "http_tools": [{"name": "get_forecast", - "method": "GET", "path": "/forecast/{city}", "read_only": true, "parameters": {"city": {"type": "string", "required": true}}}]}]}` + "description": "The forecast for a city.", "method": "GET", "path": "/forecast/{city}", "read_only": true, "parameters": {"city": {"type": "string", "required": true}}}]}]}` // TestAnImportedHTTPDefinitionIsRefused: a definition the API would store for an http connector // is refused, and writes nothing, until AI-3676 lifts it (importableDefinition). diff --git a/acceleration/internal/store/datamove_unit_test.go b/acceleration/internal/store/datamove_unit_test.go index cf65a4ebb1..2f7c9c610e 100644 --- a/acceleration/internal/store/datamove_unit_test.go +++ b/acceleration/internal/store/datamove_unit_test.go @@ -22,7 +22,7 @@ func TestImportableDefinitionSuite(t *testing.T) { func (s *ImportableDefinitionSuite) TestAnHTTPConnectorIsRefusedAndAnMCPOneKept() { http := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"http": "https://api.crm.example"}, "schemes": ["bearer"], "sources": [{"kind": "http", "endpoint": "http", - "http_tools": [{"name": "delete_item", "method": "DELETE", "path": "/items/{id}", + "http_tools": [{"name": "delete_item", "description": "Deletes an item.", "method": "DELETE", "path": "/items/{id}", "parameters": {"id": {"type": "string", "required": true}}}]}]}` mcp := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"mcp": "https://mcp.crm.example/mcp"}, "schemes": ["bearer"], "sources": [{"kind": "mcp", "endpoint": "mcp"}]}` From aed810af22af1cabd9f0d588400b60ad4a84fc12 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 04:56:07 +0100 Subject: [PATCH 04/13] [AI-3676] HTTP connectors: the API accepts http connectors (#2344) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Targets the feature branch `feature/ai-3669-http-connectors`, not `main`. Leaf 4 of 4 in the router for AI-3669 (the keystone): until it merges, no API stores an http connector. ## Why The CLI writes `connectors/http/.yaml` (base_url + tools), and the router can run such tools since leaves 1-3 (#2316 manifest, #2324 call-time safety). `POST /v1/agents/connectors` took only an MCP `endpoint`, and AI-3674 made `POST /v1/data/import` refuse an http connector until this leaf. The AI-3674 reviews asked for two things: `base_url` is checked with `egress.ValidatePublicHTTPSURL` on create and on every new revision (S1.5), and import and create open at the same time with the same checks (R1.1). ## How it works ``` POST /v1/agents/connectors (CustomConnectorRequest) ├─ endpoint set == http set (both, or neither) -> 400 "exactly one of them" ├─ scheme not on this deployment -> 400 (as before) ├─ http set │ ├─ core.CheckBaseURL(base_url) fails: over 2048, not https://, │ │ a {name}, or egress.ValidatePublicHTTPSURL refuses │ │ -> 400 "base_url must be a public https URL │ │ without userinfo, query or fragment" (AC-7, one answer) │ ├─ core.CustomManifest(base_url, tools) refuses │ │ -> 400 core's reason, naming the tool (AC-5) │ └─ ok -> store revision (the same path as MCP) └─ endpoint set: exactly as before (control test) POST /v1/data/import (importableDefinition) ├─ http source -> core.CheckBaseURL before AsCustom, the same message │ (AI-3674's refusal is gone) └─ a change set: every definition checked before applyChanges' transaction opens, so no DNS lookup runs inside it GET /v1/agents/connectors[/{id}] (connectorOf, unchanged) └─ copies fields by name: no base_url, no tools (AC-1) ``` The request shape: ``` CustomConnectorRequest ├─ endpoint string, now optional MCP server └─ http CustomHTTPAPI, new HTTP API ├─ base_url string <= 2048 └─ tools[] CustomHTTPTool, 1 to 128 ├─ name ^[A-Za-z0-9_-]{1,63}$, description <= 1000, path <= 2048 ├─ method GET|HEAD|POST|PUT|PATCH|DELETE ├─ read_only only with GET or HEAD └─ parameters {name: CustomHTTPParameter}, up to 64 type string|number|integer|boolean description <= 1000, required ``` The base_url is checked before the manifest's rules, so `http://...`, a `{name}` in it or one over 2048 gets the fixed message too (core would answer it in its own words), on create and on import alike. The schema carries core's caps and tool name pattern, and core holds them as well (a parameter's description and the base_url included), so an import, which has no request schema, stores nothing the API would refuse. Egress's own error never reaches the caller on create or import: it tells a name that does not resolve from a private one. ## Changes - `internal/api/connectors.go`: `http` beside `endpoint` on `CustomConnectorRequest` (new `CustomHTTPAPI`, `CustomHTTPTool`, `CustomHTTPParameter`, each refusing unknown fields); `customManifest` checks exactly-one and the base_url, then builds through `core.CustomManifest`. `createConnector` is untouched, so #2302 (`ReviseSynced`) merges beside it. - `internal/connectors/core`: `CheckBaseURL`, the one base_url check create and import share; `Manifest.Validate` caps a parameter's description (1000) and the http endpoint (2048). - `internal/store/datamove.go`: `importableDefinition` takes `ctx` and checks an http connector's base_url in place of AI-3674's refusal; `importableRow` checks a definition before `importRow`, and `applyChanges` runs it for the whole change set before its transaction. - The new enums name their constants (`x-enum-varnames`), so the Go SDK keeps `Array`, `Boolean`, `Null`, `Number`, `Object` and `String`; `sdks/go/acceleration/enums_test.go` pins them. - `api/openapi.yaml` and the Go, JS, Python, .NET, Ruby, Rust and PHP clients regenerated; Kotlin, Swift and Dart generate nothing new (`createConnector` is not client-accessible). - SDK note `.claude/skills/sdk/notes/2026-11-24-ai-3676.md`; `connectors` and `add-connector` skills name `http`; `sources/http/AGENTS.md` says who stores an http connector now. ## Validation | Rule | Test | | --- | --- | | AC-1: stored at revision 1 as the source's manifest; no answer shows base_url or tools | `ConnectorsSuite/TestACustomHTTPConnectorIsStoredAndItsAPIIsNeverShown` | | AC-2: a none connection validates connected; tools list says read_only | `ConnectorsSuite/TestAConnectionToAnHTTPConnectorListsItsReadOnlyTool` | | AC-5: read_only POST / DELETE -> 400 naming the tool, nothing stored | `ConnectorsSuite/TestAReadOnlyToolThatWritesIsRefusedNamingIt` | | AC-7 + S1.5: 127.0.0.1, 10.0.0.1, 169.254.169.254, http://, ::1, .invalid, query, userinfo, fragment -> one message, nothing stored | `ConnectorsSuite/TestAnHTTPConnectorWhoseAPIIsNotPublicHTTPSIsRefused` | | A new revision is checked again; a refused one leaves revision 1 | `ConnectorsSuite/TestANewRevisionOfAnHTTPConnectorIsCheckedAgain` | | Both / neither / empty endpoint -> 400 | `ConnectorsSuite/TestAConnectorWithBothOrNeitherOfEndpointAndHTTPIsRefused` | | Schema edges (method/type enums, lowercase method, unknown fields, base_url > 2048, null tools, no base_url, no type, no tool, 129 tools, bad name, description / path / parameter description over cap, 65 parameters) -> `validation_failed` | `ConnectorsSuite/TestAnHTTPToolTheSchemaRefusesIsAValidationFailure` | | Core's reasons through the API (oauth2_code, `_method`) | `ConnectorsSuite/TestAnHTTPConnectorTheManifestRefusesIsRefusedWithItsReason` | | Control: MCP create and its refusals answer as on 5a798ad5d (keys, values, messages from a probe run there) | `ConnectorsSuite/TestAnMCPConnectorIsAnsweredAsBefore` (passes on base and head) | | Core caps: a parameter description over 1000, a base_url over 2048 | `HTTPSourceSuite/TestAnHTTPSourceBreakingARuleIsRefused`, `ImportableDefinitionSuite/TestAnOversizedHTTPConnectorIsRefused` | | A change set's definitions are checked before its transaction opens | `store DataMoveSuite/TestAChangesDefinitionsAreCheckedBeforeItsTransactionOpens` | | Go SDK constant names kept | `sdks/go/acceleration` `TestInvocationArgumentTypeKeepsItsConstantNames`, `TestCustomHTTPToolMethodNamesItsConstants` | | Import: http kept, MCP kept; private / .invalid / http:// / {name} base_url refused with the fixed message | `ImportableDefinitionSuite`, `store DataMoveSuite/TestAnImportedHTTP*`, `api DataMoveSuite/TestAnImportedHTTPConnectorIsCheckedAsTheAPIChecksIt` | The AC tests fail on the base (run there with this branch's test file), except the schema test, which the base also passes by refusing `http` as an unknown field. Each changed condition, field copy and schema tag was mutated; the list is in the author log. ## Open points - An imported MCP definition's endpoint gets no public-address check (as on the base); the MCP source's egress client still checks each address it dials. - Breaking for SDK callers (CHANGELOG Breaking Changes): Go `CustomConnectorRequest.Endpoint` is `*string`, Rust's `endpoint` is `Option`, and PHP's and Python's constructors take `endpoint` after `schemes`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .claude/skills/add-connector/SKILL.md | 6 +- .claude/skills/connectors/SKILL.md | 2 +- .../skills/sdk/notes/2026-11-24-ai-3676.md | 1 + CHANGELOG.md | 9 + acceleration/api/openapi.yaml | 103 +++++- acceleration/internal/api/connectors.go | 104 +++++- acceleration/internal/api/connectors_test.go | 295 +++++++++++++++++- acceleration/internal/api/datamove_test.go | 22 ++ .../internal/connectors/core/custom.go | 20 ++ .../internal/connectors/core/http_tools.go | 9 +- .../connectors/core/http_tools_test.go | 20 +- .../internal/connectors/core/manifest.go | 4 + .../connectors/sources/http/AGENTS.md | 2 +- acceleration/internal/store/datamove.go | 67 ++-- acceleration/internal/store/datamove_test.go | 65 +++- .../internal/store/datamove_unit_test.go | 65 +++- .../api/default/create_connector.py | 48 +-- .../stream/_generated/models/__init__.py | 12 + .../models/custom_connector_request.py | 39 ++- .../models/custom_http_parameter.py | 65 ++++ .../models/custom_http_parameter_type.py | 31 ++ .../_generated/models/custom_http_tool.py | 105 +++++++ .../models/custom_http_tool_method.py | 33 ++ .../models/custom_http_tool_parameters.py | 67 ++++ .../_generated/models/custom_httpapi.py | 67 ++++ .../Generated/Models.cs | 102 +++++- sdks/go/acceleration/enums_test.go | 36 +++ sdks/go/acceleration/generated.go | 138 ++++++-- sdks/js/src/generated/api.ts | 44 ++- .../src/Generated/CustomConnectorRequest.php | 20 +- sdks/php/src/Generated/CustomHTTPAPI.php | 48 +++ .../php/src/Generated/CustomHTTPParameter.php | 53 ++++ sdks/php/src/Generated/CustomHTTPTool.php | 67 ++++ .../getstream/vision_agents/generated/spec.rb | 16 +- sdks/rust/src/operations.rs | 2 +- sdks/rust/src/types.rs | 169 +++++++++- 36 files changed, 1818 insertions(+), 138 deletions(-) create mode 100644 .claude/skills/sdk/notes/2026-11-24-ai-3676.md create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter_type.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_method.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_parameters.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/custom_httpapi.py create mode 100644 sdks/php/src/Generated/CustomHTTPAPI.php create mode 100644 sdks/php/src/Generated/CustomHTTPParameter.php create mode 100644 sdks/php/src/Generated/CustomHTTPTool.php diff --git a/.claude/skills/add-connector/SKILL.md b/.claude/skills/add-connector/SKILL.md index d72c844022..e35e6fb904 100644 --- a/.claude/skills/add-connector/SKILL.md +++ b/.claude/skills/add-connector/SKILL.md @@ -16,11 +16,15 @@ First decide which kind you need. Connecting an existing connector to an agent i ## A custom connector Dashboard: **Library › Connectors › New connector**. API: `POST /v1/agents/connectors` -(`CustomConnectorRequest`: `id`, `name`, `endpoint`, `schemes`, optional `scopes`, +(`CustomConnectorRequest`: `id`, `name`, `endpoint` or `http`, `schemes`, optional `scopes`, `client`, `category`, `description`). - The id starts with `custom_`, for example `custom_crm`. Built-ins never use that prefix. - `endpoint` is the MCP server's https URL. +- `http` is an HTTP API in place of an MCP server: `base_url` and `tools`, each tool with + `name`, `description`, `method`, `path`, `parameters` and `read_only` (only on a GET or a + HEAD). Send `endpoint` or `http`, not both. `base_url` must be a public https URL, and it is + never shown again. `oauth2_code` is not available for one. - `schemes` is how a connection signs in: `oauth2_code`, `bearer`, `api_key`, or `none`. - A public server that needs no credential takes `schemes: ["none"]`. Create the connection, then connect it with `PUT /v1/agents/connections/{id}/credentials` and the body diff --git a/.claude/skills/connectors/SKILL.md b/.claude/skills/connectors/SKILL.md index f86b2b622e..ce8d29a9f3 100644 --- a/.claude/skills/connectors/SKILL.md +++ b/.claude/skills/connectors/SKILL.md @@ -65,7 +65,7 @@ The same with the API (operations in `acceleration/api/openapi.yaml`): |---|---| | The catalog | `GET /v1/agents/connectors` | | The app's own OAuth client | `PUT /v1/agents/connectors/{id}/oauth-client` | -| A custom MCP connector | `POST /v1/agents/connectors` (`id` starts with `custom_`) | +| A custom MCP or HTTP API connector | `POST /v1/agents/connectors` (`id` starts with `custom_`; `endpoint` or `http`) | | A connection | `POST /v1/agents/connections` (`connector_id`, `owner`, `auth_scheme`) | | OAuth consent | `POST /v1/agents/connections/{id}/authorizations` → open `launch_url` in a popup | | A token or key | `PUT /v1/agents/connections/{id}/credentials` | diff --git a/.claude/skills/sdk/notes/2026-11-24-ai-3676.md b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md new file mode 100644 index 0000000000..75c3fcf685 --- /dev/null +++ b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md @@ -0,0 +1 @@ +`createConnector` (`POST /v1/agents/connectors`) takes an HTTP API in place of an MCP server (AI-3676). `CustomConnectorRequest` has a new optional `http`, a `CustomHTTPAPI` `{base_url, tools}`. Each tool is a `CustomHTTPTool` `{name, description, method, path, parameters, read_only}`: `method` is one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH` and `DELETE`, and `parameters` maps a name to a `CustomHTTPParameter` `{type, description, required}`, whose `type` is one of `string`, `number`, `integer` and `boolean`. `endpoint` is no longer required: a request sends a non-empty `endpoint` or `http`, not both. This breaks existing callers in four SDKs. In Go, `CustomConnectorRequest.Endpoint` is now a `*string` (`sdks/go/acceleration/generated.go`), and a caller that set it as a string now sets a pointer. In Rust, `CustomConnectorRequest.endpoint` is now an `Option` (`sdks/rust/src/types.rs`), so a struct literal or a read of a `String` no longer compiles. In PHP (`sdks/php/src/Generated/CustomConnectorRequest.php`) and Python (`plugins/stream`, `_generated/models/custom_connector_request.py`), `endpoint` moves from the first constructor argument to after `schemes`, so a positional call no longer matches; named and keyword arguments still work. The `Connector` the router answers is unchanged, so it shows neither `base_url` nor the tools. Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients. Other SDKs need to update: a `connectors.create` resource method, where an SDK has one, takes `http` beside `endpoint`. Swift, Kotlin and Dart need nothing, since `createConnector` is not client-accessible. diff --git a/CHANGELOG.md b/CHANGELOG.md index c64ab679e0..625be5cdcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -710,6 +710,15 @@ Every reply the agent abandons logs one INFO line, `the agent was interrupted`, ## Breaking Changes +### `CustomConnectorRequest`'s endpoint is optional in the Go, Rust, PHP and Python SDKs + +`POST /v1/agents/connectors` now takes either an MCP `endpoint` or an `http` block with a `base_url` and its tools, so `endpoint` is optional in every generated `CustomConnectorRequest` (AI-3676): + +- Go: `CustomConnectorRequest.Endpoint` is now `*string`. Set it with a pointer (for example `Endpoint: &url`); a caller that set a plain string no longer compiles. +- Rust: `CustomConnectorRequest.endpoint` is now `Option`. Set it with `Some(url)`; a struct literal with a plain `String`, or a read of one, no longer compiles. +- PHP: the `CustomConnectorRequest` constructor takes `$endpoint` after `$schemes`, not first. A positional call no longer matches; named arguments work as before. +- Python (`plugins/stream`): the generated `CustomConnectorRequest` takes `endpoint` after `schemes`, not first. A positional call no longer matches; keyword arguments work as before. + ### The Go SDK reads no items for a turn with no id `AgentResponse.Items`, on the handle `Responses.Create` returns, fails with `client.ErrUnnamedTurn` when the turn has no id: the router names none for an incognito session, a speech-to-speech session or the retry of a `request_id` already taken. It used to read every turn in the session instead, passed off as this turn's; a caller that relied on that now gets the error, and reads `Session.Responses.Items` for the whole session or follows `Session.Events` (AI-3571). diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 02e352415b..908ad78130 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -4652,7 +4652,7 @@ components: type: object CustomConnectorRequest: additionalProperties: false - description: A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. + description: A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. properties: category: maxLength: 80 @@ -4663,9 +4663,12 @@ components: maxLength: 1000 type: string endpoint: - description: 'The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused.' + description: 'The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both.' maxLength: 2048 type: string + http: + $ref: '#/components/schemas/CustomHTTPAPI' + description: An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. id: description: Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. pattern: ^custom_[a-z][a-z0-9_]{0,56}$ @@ -4695,9 +4698,99 @@ components: required: - id - name - - endpoint - schemes type: object + CustomHTTPAPI: + additionalProperties: false + description: An HTTP API a custom connector calls, and the tools it offers an agent. + properties: + base_url: + description: 'The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored.' + maxLength: 2048 + type: string + tools: + description: At least one and at most 128, each name once. + items: + $ref: '#/components/schemas/CustomHTTPTool' + maxItems: 128 + minItems: 1 + type: array + required: + - base_url + - tools + type: object + CustomHTTPParameter: + additionalProperties: false + description: One value the model gives an http tool. + properties: + description: + maxLength: 1000 + type: string + required: + description: The model must give it. A parameter in the path must be required. + type: boolean + type: + enum: + - string + - number + - integer + - boolean + type: string + x-enum-varnames: + - CustomHTTPParameterTypeString + - CustomHTTPParameterTypeNumber + - CustomHTTPParameterTypeInteger + - CustomHTTPParameterTypeBoolean + required: + - type + type: object + CustomHTTPTool: + additionalProperties: false + description: 'One tool of an http connector: one request, whose method and path are fixed.' + properties: + description: + description: What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + maxLength: 1000 + type: string + method: + enum: + - GET + - HEAD + - POST + - PUT + - PATCH + - DELETE + type: string + x-enum-varnames: + - CustomHTTPToolMethodGET + - CustomHTTPToolMethodHEAD + - CustomHTTPToolMethodPOST + - CustomHTTPToolMethodPUT + - CustomHTTPToolMethodPATCH + - CustomHTTPToolMethodDELETE + name: + description: 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + pattern: ^[A-Za-z0-9_-]{1,63}$ + type: string + parameters: + additionalProperties: + $ref: '#/components/schemas/CustomHTTPParameter' + description: The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + maxProperties: 64 + type: object + path: + description: Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + maxLength: 2048 + type: string + read_only: + description: The tool only reads. Only a GET or HEAD tool may say so. + type: boolean + required: + - name + - description + - method + - path + type: object CustomModel: properties: base_url: @@ -16243,7 +16336,7 @@ paths: summary: List or search connectors post: description: |- - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. operationId: createConnector @@ -16281,7 +16374,7 @@ paths: $ref: '#/components/responses/InternalError' "503": $ref: '#/components/responses/Unavailable' - summary: Add a custom MCP connector + summary: Add a custom connector /v1/agents/connectors/{id}: delete: description: |- diff --git a/acceleration/internal/api/connectors.go b/acceleration/internal/api/connectors.go index 9375c644eb..c6e695bc76 100644 --- a/acceleration/internal/api/connectors.go +++ b/acceleration/internal/api/connectors.go @@ -152,7 +152,7 @@ type ConnectorPage struct { NextCursor *string `json:"next_cursor,omitempty" doc:"Pass as cursor for the next page, with the same q. Absent on the last one."` } -// CustomConnectorRequest is a custom MCP server for the app's agents to connect to. +// CustomConnectorRequest is a custom MCP server or HTTP API for the app's agents to connect to. // // The limits on name, category and description are the prototype's // (CreateConnectorDefinitionRequest in api/openapi.yaml on codex/connector-support at @@ -168,19 +168,77 @@ type CustomConnectorRequest struct { Name string `json:"name" minLength:"1" maxLength:"120"` Category string `json:"category,omitempty" maxLength:"80"` Description string `json:"description,omitempty" maxLength:"1000"` - Endpoint string `json:"endpoint" maxLength:"2048" doc:"The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused."` + Endpoint string `json:"endpoint,omitempty" maxLength:"2048" doc:"The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both."` + HTTP *CustomHTTPAPI `json:"http,omitempty" doc:"An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both."` Schemes []string `json:"schemes" minItems:"1" doc:"How a connection may authenticate. Each must be a scheme this deployment has, except oauth2_client_credentials, which a custom connector cannot use: it needs a token endpoint a custom connector cannot set."` Scopes []string `json:"scopes,omitempty" maxItems:"100" uniqueItems:"true" pattern:"^[!#-\\[\\]-~]+$" patternDescription:"an RFC 6749 scope token" doc:"The scopes a consent asks for, each an RFC 6749 scope token."` Client *ConnectorClient `json:"client,omitempty"` } func (*CustomConnectorRequest) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { - schema.Description = "A custom MCP server for the app's agents to connect to. An unknown " + + schema.Description = "A custom MCP server or HTTP API for the app's agents to connect to. An unknown " + "field is refused rather than ignored." schema.AdditionalProperties = false return schema } +// CustomHTTPAPI is an http connector's API and its tools (core.CustomConnector's BaseURL and +// Tools). The schema carries the caps and the tool name pattern of core.Manifest.Validate +// (maxHTTPTools, maxHTTPToolDescription, maxHTTPPath, maxHTTPParameters and httpToolName in +// internal/connectors/core/http_tools.go), so a request breaking one fails validation. Huma +// counts a length in characters and core in bytes, so core still refuses a description whose +// characters fit and bytes do not. The other rules are core's alone (checkHTTPSource), which +// answer naming the tool. +type CustomHTTPAPI struct { + BaseURL string `json:"base_url" maxLength:"2048" doc:"The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored."` + Tools []CustomHTTPTool `json:"tools" nullable:"false" minItems:"1" maxItems:"128" doc:"At least one and at most 128, each name once."` +} + +func (*CustomHTTPAPI) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "An HTTP API a custom connector calls, and the tools it offers an agent." + schema.AdditionalProperties = false + return schema +} + +// CustomHTTPTool is one tool of an http connector (core.HTTPTool). Its methods and parameter +// types are core's (httpMethods and httpParameterTypes in internal/connectors/core/http_tools.go). +type CustomHTTPTool struct { + Name string `json:"name" pattern:"^[A-Za-z0-9_-]{1,63}$" doc:"1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __."` + Description string `json:"description" maxLength:"1000" doc:"What the tool does, which the model reads to know when to use it. Up to 1000 bytes."` + Method string `json:"method" enum:"GET,HEAD,POST,PUT,PATCH,DELETE"` + Path string `json:"path" maxLength:"2048" doc:"Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required."` + Parameters map[string]CustomHTTPParameter `json:"parameters,omitempty" maxProperties:"64" doc:"The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused."` + ReadOnly bool `json:"read_only,omitempty" doc:"The tool only reads. Only a GET or HEAD tool may say so."` +} + +func (*CustomHTTPTool) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One tool of an http connector: one request, whose method and path are fixed." + schema.AdditionalProperties = false + // Named, so the next enum with one of these values does not rename the Go SDK's constants, + // as ConnectionOwnerType's are (connections.go). + schema.Properties["method"].Extensions = map[string]any{"x-enum-varnames": []string{"CustomHTTPToolMethodGET", + "CustomHTTPToolMethodHEAD", "CustomHTTPToolMethodPOST", "CustomHTTPToolMethodPUT", "CustomHTTPToolMethodPATCH", + "CustomHTTPToolMethodDELETE"}} + return schema +} + +// CustomHTTPParameter is one value the model gives an http tool (core.HTTPParameter). +type CustomHTTPParameter struct { + Type string `json:"type" enum:"string,number,integer,boolean"` + Description string `json:"description,omitempty" maxLength:"1000"` + Required bool `json:"required,omitempty" doc:"The model must give it. A parameter in the path must be required."` +} + +func (*CustomHTTPParameter) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One value the model gives an http tool." + schema.AdditionalProperties = false + // InvocationArgumentType has string, number and boolean too: unnamed, oapi-codegen would + // prefix both enums' constants (enumsConflict), renaming the Go SDK's String, Number and the rest. + schema.Properties["type"].Extensions = map[string]any{"x-enum-varnames": []string{"CustomHTTPParameterTypeString", + "CustomHTTPParameterTypeNumber", "CustomHTTPParameterTypeInteger", "CustomHTTPParameterTypeBoolean"}} + return schema +} + type listConnectorsRequest struct { // 120 is the longest name a custom definition may have, which is what a picker's // search box looks for. @@ -244,8 +302,8 @@ func (s *Server) registerConnectors(api huma.API) { OperationID: "createConnector", Method: http.MethodPost, Path: "/v1/agents/connectors", - Summary: "Add a custom MCP connector", - Description: "Stores a custom MCP server as one of the app's connectors. Sending an " + + Summary: "Add a custom connector", + Description: "Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an " + "id the app already has stores its next revision, which connections pick up when " + "they reconnect; sending the same definition again changes nothing. A built-in " + "cannot be changed this way.\n\n" + @@ -331,7 +389,7 @@ func (s *Server) getConnector(ctx context.Context, request *getConnectorRequest) return &connectorResponse{Body: connectorOf(definition, s.publicURL)}, nil } -// createConnector stores a custom MCP definition as the caller's own. +// createConnector stores a custom MCP or http definition as the caller's own. func (s *Server) createConnector(ctx context.Context, request *createConnectorRequest) (*connectorResponse, error) { customerID, ok := CustomerFrom(ctx) if !ok { @@ -409,8 +467,11 @@ func namedFew(names []string) string { return fmt.Sprintf("%s and %d more", strings.Join(names[:usesNamed], ", "), len(names)-usesNamed) } -// customManifest is the manifest a custom MCP definition is stored as, or why it cannot be. +// customManifest is the manifest a custom MCP or http definition is stored as, or why it cannot be. func (s *Server) customManifest(ctx context.Context, sent CustomConnectorRequest) (core.Manifest, error) { + if (sent.Endpoint == "") == (sent.HTTP == nil) { + return core.Manifest{}, stack.Wrap(errors.New("a custom connector has an MCP endpoint or an http API, and exactly one of them")) + } known := slices.Sorted(maps.Keys(s.connectors.Schemes)) for _, scheme := range sent.Schemes { if !slices.Contains(known, scheme) { @@ -429,13 +490,24 @@ func (s *Server) customManifest(ctx context.Context, sent CustomConnectorRequest client.AuthMethod = core.ClientAuthMethod(sent.Client.AuthMethod) client.Alg = sent.Client.Alg } - manifest, err := core.CustomManifest(core.CustomConnector{ + custom := core.CustomConnector{ ID: sent.ID, Name: sent.Name, Category: sent.Category, Description: sent.Description, Endpoint: sent.Endpoint, Schemes: sent.Schemes, Scopes: sent.Scopes, Client: client, - }) + } + if sent.HTTP != nil { + // Before the manifest's rules, so every base_url refused gets one answer. + if err := core.CheckBaseURL(ctx, sent.HTTP.BaseURL); err != nil { + return core.Manifest{}, err + } + custom.BaseURL, custom.Tools = sent.HTTP.BaseURL, httpTools(sent.HTTP.Tools) + } + manifest, err := core.CustomManifest(custom) if err != nil { return core.Manifest{}, err } + if sent.HTTP != nil { + return manifest, nil + } // Last, since it resolves the host: the checks above cost nothing. // One answer for every refusal: egress's own errors tell a name that does not resolve from // one that resolves to a private address, which would let a caller probe the names the @@ -446,6 +518,20 @@ func (s *Server) customManifest(ctx context.Context, sent CustomConnectorRequest return manifest, nil } +// httpTools is sent as core's tools, field by field. +func httpTools(sent []CustomHTTPTool) []core.HTTPTool { + tools := make([]core.HTTPTool, 0, len(sent)) + for _, tool := range sent { + parameters := make(map[string]core.HTTPParameter, len(tool.Parameters)) + for name, parameter := range tool.Parameters { + parameters[name] = core.HTTPParameter{Type: parameter.Type, Description: parameter.Description, Required: parameter.Required} + } + tools = append(tools, core.HTTPTool{Name: tool.Name, Description: tool.Description, Method: tool.Method, + Path: tool.Path, Parameters: parameters, ReadOnly: tool.ReadOnly}) + } + return tools +} + // connectorOf is the part of a stored definition a caller is shown. Each field is // copied by name, so a field added to the manifest stays hidden until it is added here. // publicURL is the router's, which an oauth2_code connector's redirect URI is built from as a diff --git a/acceleration/internal/api/connectors_test.go b/acceleration/internal/api/connectors_test.go index 113784d546..43023818f5 100644 --- a/acceleration/internal/api/connectors_test.go +++ b/acceleration/internal/api/connectors_test.go @@ -16,6 +16,8 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/providers" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/none" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) @@ -29,14 +31,16 @@ func TestConnectorsSuite(t *testing.T) { runSuite(t, new(ConnectorsSuite)) } -// SetupSuite registers the scheme the built-ins name, and seeds the built-ins as a router -// start does. Seeding is idempotent, so suites running beside this one see the same rows. +// SetupSuite registers the scheme the built-ins name, none and the http source, for a +// connection to an http connector, and seeds the built-ins as a router start does. Seeding is +// idempotent, so suites running beside this one see the same rows. func (s *ConnectorsSuite) SetupSuite() { s.connectors = core.Registry{Schemes: map[string]core.Scheme{ "oauth2_code": namedScheme("oauth2_code"), "oauth2_client_credentials": namedScheme("oauth2_client_credentials"), "api_key": namedScheme("api_key"), - }} + none.Name: none.New(), + }, ToolSources: map[string]core.ToolSource{httpsource.Kind: httpsource.New()}} s.RouterSuite.SetupSuite() s.Require().NoError(s.store.ConnectorDefinitions.Seed(context.Background(), providers.FS)) } @@ -757,6 +761,291 @@ WHERE datname = current_database() AND wait_event_type = 'Lock' return count } +// TestAnMCPConnectorIsAnsweredAsBefore is the control for AI-3676: a custom MCP connector's +// create, and the refusals of its endpoint, answer as on 5a798ad5d, probed there with this +// request (AI-3676/base-probe.txt): the same keys and values, and the same messages. +func (s *ConnectorsSuite) TestAnMCPConnectorIsAnsweredAsBefore() { + id := s.customID() + status, raw := s.serverClient.call(http.MethodPost, "/v1/agents/connectors", s.customConnector(id)) + + s.Require().Equal(http.StatusOK, status) + var shown map[string]any + s.Require().NoError(json.Unmarshal(raw, &shown)) + s.Equal([]string{"channel", "client", "created_at", "custom", "duration", "id", "inputs", "name", "revision", "schemes", "scopes"}, + slices.Sorted(maps.Keys(shown))) + for _, key := range []string{"created_at", "duration"} { + delete(shown, key) + } + s.Equal(map[string]any{"channel": false, "client": map[string]any{"registration": []any{"dcr"}}, "custom": true, "id": id, + "inputs": []any{}, "name": "Our CRM", "revision": float64(1), "schemes": []any{"oauth2_code"}, "scopes": []any{}}, shown) + + for endpoint, message := range map[string]string{ + "https://10.0.0.7/mcp": "endpoint must be a public https URL without userinfo, query or fragment", + "https://8.8.8.8/mcp?x=1": "endpoint must be a public https URL without userinfo, query or fragment", + "http://8.8.8.8/mcp": `manifest "%s": endpoints.mcp: "http://8.8.8.8/mcp" does not start with https:// or a placeholder`, + } { + sent := s.customConnector(s.customID()) + sent["endpoint"] = endpoint + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, endpoint) + s.Equal(strings.ReplaceAll(message, "%s", sent["id"].(string)), failure, endpoint) + } +} + +// TestACustomHTTPConnectorIsStoredAndItsAPIIsNeverShown is AC-1 of AI-3669 through the API: +// open_meteo's file as the CLI posts it is stored at revision 1 as the manifest the http +// source runs, and no answer shows its base URL or its tools. +func (s *ConnectorsSuite) TestACustomHTTPConnectorIsStoredAndItsAPIIsNeverShown() { + id := s.customID() + + created := s.create(s.httpConnector(id)) + + s.Equal(id, created.ID) + s.Equal(1, created.Revision) + s.True(created.Custom) + s.Equal([]string{none.Name}, created.Schemes) + s.Equal(created, s.get(id), "the answer to the create is the stored row") + stored, err := s.store.ConnectorDefinitions.Latest(context.Background(), s.customerID(), id) + s.Require().NoError(err) + s.Equal(map[string]string{core.SourceKindHTTP: "https://8.8.8.8"}, stored.Manifest.Endpoints) + s.Equal([]core.SourceRule{{Kind: core.SourceKindHTTP, Endpoint: core.SourceKindHTTP, HTTPTools: []core.HTTPTool{{ + Name: "get_forecast", Description: "The weather at a place.", Method: http.MethodGet, Path: "/v1/forecast", ReadOnly: true, + Parameters: map[string]core.HTTPParameter{ + "latitude": {Type: "number", Description: "Degrees north.", Required: true}, + "longitude": {Type: "number", Description: "Degrees east.", Required: true}, + "current": {Type: "string"}, + }}}}}, stored.Manifest.Sources) + for _, path := range []string{"/v1/agents/connectors/" + id, "/v1/agents/connectors?limit=200"} { + status, raw := s.serverClient.call(http.MethodGet, path, nil) + s.Require().Equal(http.StatusOK, status) + s.Contains(string(raw), id, path) + for _, hidden := range []string{"8.8.8.8", "base_url", `"http"`, "/v1/forecast", "get_forecast"} { + s.NotContains(string(raw), hidden, path) + } + } +} + +// TestAConnectionToAnHTTPConnectorListsItsReadOnlyTool is AC-2 of AI-3669 through the API: a +// connection with scheme none validates as connected, and its tools listing says the GET +// tool only reads. Discover sends nothing (internal/connectors/sources/http), so the API at +// the public address is never called. +func (s *ConnectorsSuite) TestAConnectionToAnHTTPConnectorListsItsReadOnlyTool() { + id := s.customID() + sent := s.httpConnector(id) + tools := sent["http"].(map[string]any)["tools"].([]map[string]any) + sent["http"].(map[string]any)["tools"] = append(tools, map[string]any{ + "name": "add_note", "description": "Adds a note.", "method": "POST", "path": "/v1/notes", + "parameters": map[string]any{"text": map[string]any{"type": "string", "required": true}}}, + // A GET tool is read-only only when the file says so. + map[string]any{"name": "list_notes", "description": "Lists the notes.", "method": "GET", "path": "/v1/notes"}) + s.create(sent) + var created Connection + s.Require().Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/connections", appOwned(id), &created)) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/agents/connections/"+created.ID+"/credentials", + map[string]any{"expected_revision": 1}, nil)) + + var validation ConnectionValidation + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/connections/"+created.ID+"/validate", nil, &validation)) + var listed ConnectionTools + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/connections/"+created.ID+"/tools", nil, &listed)) + + s.Equal(validationConnected, string(validation.Status), validation.Error) + readOnly := map[string]bool{} + for _, tool := range listed.Tools { + readOnly[tool.Name] = tool.ReadOnly + } + s.Equal(map[string]bool{"get_forecast": true, "add_note": false, "list_notes": false}, readOnly) +} + +// TestAReadOnlyToolThatWritesIsRefusedNamingIt is AC-5 of AI-3669 through the API: a POST or +// a DELETE tool saying read_only is a 400 naming the tool, and nothing is stored. +func (s *ConnectorsSuite) TestAReadOnlyToolThatWritesIsRefusedNamingIt() { + for _, method := range []string{http.MethodPost, http.MethodDelete} { + id := s.customID() + sent := s.httpConnector(id) + tool := sent["http"].(map[string]any)["tools"].([]map[string]any)[0] + tool["name"], tool["method"] = "remove_forecast", method + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, method) + s.Contains(failure, fmt.Sprintf(`a read-only tool must be GET or HEAD, and "remove_forecast" is %s`, method)) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), method) + } +} + +// TestAnHTTPConnectorWhoseAPIIsNotPublicHTTPSIsRefused is AC-7 of AI-3669 through the API, +// with AI-3674 S1.5's addresses and a few more: each is a 400 with one fixed message, so a +// caller cannot tell a name that does not resolve from a private one, and nothing is stored. +func (s *ConnectorsSuite) TestAnHTTPConnectorWhoseAPIIsNotPublicHTTPSIsRefused() { + for _, base := range []string{ + "https://127.0.0.1", // loopback + "https://10.0.0.1", // private-use, RFC 1918 + "https://169.254.169.254", // link-local, where cloud metadata servers answer + "http://api.open-meteo.com", // not https + "https://[::1]", // IPv6 loopback + "https://router-probe.invalid", // .invalid never resolves, RFC 6761 section 6.4 + "https://8.8.8.8/v1?key=secret", // a query + "https://user:secret@8.8.8.8", // userinfo + "https://8.8.8.8/v1#top", // a fragment + "HTTPS://8.8.8.8", // public to egress, which reads the scheme in any case, not to the manifest's rules + "https://8.8.8.8/{x}", // a {name} the manifest's rules refuse, since a custom connector declares no input + } { + id := s.customID() + sent := s.httpConnector(id) + sent["http"].(map[string]any)["base_url"] = base + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, base) + s.Equal("base_url must be a public https URL without userinfo, query or fragment", failure, base) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), base) + } +} + +// TestANewRevisionOfAnHTTPConnectorIsCheckedAgain: AI-3674 S1.5, the base URL is checked on +// every revision as on the first. A refused one leaves the stored revision as it was. +func (s *ConnectorsSuite) TestANewRevisionOfAnHTTPConnectorIsCheckedAgain() { + id := s.customID() + s.Equal(1, s.create(s.httpConnector(id)).Revision) + private := s.httpConnector(id) + private["http"].(map[string]any)["base_url"] = "https://169.254.169.254/v1" + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", private) + + s.Equal(http.StatusBadRequest, status) + s.Equal("base_url must be a public https URL without userinfo, query or fragment", failure) + stored, err := s.store.ConnectorDefinitions.Latest(context.Background(), s.customerID(), id) + s.Require().NoError(err) + s.Equal(1, stored.Revision) + s.Equal("https://8.8.8.8", stored.Manifest.Endpoints[core.SourceKindHTTP]) + moved := s.httpConnector(id) + moved["http"].(map[string]any)["base_url"] = "https://1.1.1.1" + s.Equal(2, s.create(moved).Revision) +} + +// TestAConnectorWithBothOrNeitherOfEndpointAndHTTPIsRefused: a custom connector is an MCP +// server or an http API, so one naming both or neither is refused and nothing is stored. +func (s *ConnectorsSuite) TestAConnectorWithBothOrNeitherOfEndpointAndHTTPIsRefused() { + both := s.httpConnector(s.customID()) + both["endpoint"] = "https://8.8.8.8/mcp" + neither := s.customConnector(s.customID()) + delete(neither, "endpoint") + empty := s.customConnector(s.customID()) + empty["endpoint"] = "" + for name, sent := range map[string]map[string]any{"both": both, "neither": neither, "an empty endpoint": empty} { + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, name) + s.Equal("a custom connector has an MCP endpoint or an http API, and exactly one of them", failure, name) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+sent["id"].(string), nil, nil), name) + } +} + +// TestAnHTTPConnectorTheManifestRefusesIsRefusedWithItsReason: an http block the schema takes +// but the manifest's rules refuse is a 400 with core's reason, and nothing is stored. +func (s *ConnectorsSuite) TestAnHTTPConnectorTheManifestRefusesIsRefusedWithItsReason() { + for name, test := range map[string]struct { + change func(sent, api map[string]any) + reason string + }{ + "oauth2_code": {func(sent, _ map[string]any) { + sent["schemes"], sent["client"] = []string{"oauth2_code"}, map[string]any{"registration": []string{"dcr"}} + }, "oauth2_code is not available for an http custom connector"}, + "a method override parameter": {func(_, api map[string]any) { + api["tools"].([]map[string]any)[0]["parameters"].(map[string]any)["_method"] = map[string]any{"type": "string"} + }, "parameters._method: names a method override"}, + } { + id := s.customID() + sent := s.httpConnector(id) + test.change(sent, sent["http"].(map[string]any)) + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, name) + s.Contains(failure, test.reason, name) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), name) + } +} + +// TestAnHTTPToolTheSchemaRefusesIsAValidationFailure: what the request's schema says of an +// http block (CustomHTTPAPI) is held before any rule of the manifest, an unknown field included. +func (s *ConnectorsSuite) TestAnHTTPToolTheSchemaRefusesIsAValidationFailure() { + for name, change := range map[string]func(api, tool, parameter map[string]any){ + "a method that is not one of the six": func(_, tool, _ map[string]any) { tool["method"] = "TRACE" }, + "a lowercase method": func(_, tool, _ map[string]any) { tool["method"] = "get" }, + "a parameter type that is no scalar": func(_, _, parameter map[string]any) { parameter["type"] = "object" }, + "a base_url over 2048": func(api, _, _ map[string]any) { api["base_url"] = "https://8.8.8.8/" + strings.Repeat("a", 2033) }, + "a header on a tool": func(_, tool, _ map[string]any) { + tool["headers"] = map[string]string{"X-HTTP-Method-Override": "DELETE"} + }, + "an unknown field of the api": func(api, _, _ map[string]any) { api["headers"] = map[string]string{"X-HTTP-Method-Override": "DELETE"} }, + "an unknown field of a parameter": func(_, _, parameter map[string]any) { parameter["in"] = "header" }, + "no base_url": func(api, _, _ map[string]any) { delete(api, "base_url") }, + "tools null": func(api, _, _ map[string]any) { api["tools"] = nil }, + "a parameter with no type": func(_, _, parameter map[string]any) { delete(parameter, "type") }, + // AI-3676 R1.4: core's caps and tool name pattern, which the schema carries. + "no tool": func(api, _, _ map[string]any) { api["tools"] = []any{} }, + "129 tools": func(api, tool, _ map[string]any) { + tools := make([]map[string]any, 129) + for i := range tools { + tools[i] = maps.Clone(tool) + tools[i]["name"] = fmt.Sprintf("tool_%d", i) + } + api["tools"] = tools + }, + "a name of 64": func(_, tool, _ map[string]any) { tool["name"] = strings.Repeat("n", 64) }, + "a name with a dot": func(_, tool, _ map[string]any) { tool["name"] = "get.forecast" }, + "a description over 1000": func(_, tool, _ map[string]any) { tool["description"] = strings.Repeat("d", 1001) }, + "a path over 2048": func(_, tool, _ map[string]any) { tool["path"] = "/" + strings.Repeat("p", 2048) }, + "a parameter description over 1000": func(_, _, parameter map[string]any) { parameter["description"] = strings.Repeat("d", 1001) }, + "65 parameters": func(_, tool, _ map[string]any) { + parameters := tool["parameters"].(map[string]any) + for i := len(parameters); i < 65; i++ { + parameters[fmt.Sprintf("p%d", i)] = map[string]any{"type": "string"} + } + }, + } { + id := s.customID() + sent := s.httpConnector(id) + api := sent["http"].(map[string]any) + tool := api["tools"].([]map[string]any)[0] + change(api, tool, tool["parameters"].(map[string]any)["latitude"].(map[string]any)) + + status, raw := s.serverClient.call(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, name) + var answered ErrorResponse + s.Require().NoError(json.Unmarshal(raw, &answered), name) + s.Equal("validation_failed", answered.Error.Code, "%s: %s", name, raw) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), name) + } +} + +// httpConnector is AC-1 of AI-3669's open_meteo as the CLI posts it, scheme none, at a public +// IP literal, so checking it resolves nothing. +func (s *ConnectorsSuite) httpConnector(id string) map[string]any { + return map[string]any{ + "id": id, + "name": "Open-Meteo", + "schemes": []string{none.Name}, + "http": map[string]any{ + "base_url": "https://8.8.8.8", + "tools": []map[string]any{{ + "name": "get_forecast", "description": "The weather at a place.", "method": "GET", "path": "/v1/forecast", + "read_only": true, + "parameters": map[string]any{ + "latitude": map[string]any{"type": "number", "description": "Degrees north.", "required": true}, + "longitude": map[string]any{"type": "number", "description": "Degrees east.", "required": true}, + "current": map[string]any{"type": "string"}, + }, + }}, + }, + } +} + // customConnector is a custom MCP connector the router accepts. Its endpoint is a public IP // literal, so checking it resolves nothing. func (s *ConnectorsSuite) customConnector(id string) map[string]any { diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index f2801e2d6a..7ceb0ca092 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -224,6 +224,28 @@ func (s *DataMoveSuite) TestAnImportedConnectorNamingTheOperatorsClientAfterAnot s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+refused, nil, nil)) } +// TestAnImportedHTTPConnectorIsCheckedAsTheAPIChecksIt: POST /v1/data/import takes an http +// connector the API would create (AI-3676), and refuses one whose API is on a private address +// with the create's own message, storing nothing. +func (s *DataMoveSuite) TestAnImportedHTTPConnectorIsCheckedAsTheAPIChecksIt() { + refused, taken := "custom_"+store.NewID(), "custom_"+store.NewID() + line := func(id, base string) dataLine { + return dataLine{Table: "connector_definitions", Row: json.RawMessage(`{"id": "` + id + `", "revision": 1, "name": "Acme", + "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": {"id": "` + id + `", "revision": 1, + "name": "Acme", "schemes": ["api_key"], "endpoints": {"http": "` + base + `"}, "sources": [{"kind": "http", "endpoint": "http", + "http_tools": [{"name": "get_item", "description": "Reads an item.", "method": "GET", "path": "/items", "read_only": true}]}]}}`)} + } + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import?full=true", ndjson([]dataLine{line(refused, "https://10.0.0.1")})) + taking := s.serverClient.do(http.MethodPost, "/v1/data/import?full=true", ndjson([]dataLine{line(taken, "https://8.8.8.8")}), nil) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure, "base_url must be a public https URL without userinfo, query or fragment") + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+refused, nil, nil)) + s.Equal(http.StatusOK, taking) + s.Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+taken, nil, nil)) +} + // A database that fails is the router's failure, and its text names the database's address. func (s *DataMoveSuite) TestAnImportTheDatabaseCannotWriteIsAFailureWithNoDatabaseText() { id := "custom_" + store.NewID() diff --git a/acceleration/internal/connectors/core/custom.go b/acceleration/internal/connectors/core/custom.go index c654c0b3ce..f0d9bab008 100644 --- a/acceleration/internal/connectors/core/custom.go +++ b/acceleration/internal/connectors/core/custom.go @@ -1,11 +1,13 @@ package core import ( + "context" "encoding/json" "errors" "slices" "strings" + "github.com/GetStream/Vision-Agents/acceleration/internal/egress" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) @@ -28,6 +30,24 @@ type CustomConnector struct { Client ClientPolicy } +// CheckBaseURL is nil for a base URL an http custom connector may have, and one answer for every +// other: a caller who creates or imports one (customManifest in internal/api/connectors.go, +// importableDefinition in internal/store/datamove.go) checks it before CustomManifest, whose +// rules would answer some of them in their own words (AC-7 of AI-3669). One answer, since +// egress's own errors tell a name that does not resolve from one that resolves to a private +// address, which would let a caller probe the names the router's resolver knows. It resolves +// the host, last, after the checks that cost nothing. +func CheckBaseURL(ctx context.Context, baseURL string) error { + // The endpoint rules Manifest.Validate holds an http custom connector's base URL to: its + // cap, and checkTemplate's for a manifest that declares no input, capture or var, where a + // URL starts with https:// and a {name} names nothing. + if len(baseURL) > maxHTTPPath || !strings.HasPrefix(baseURL, "https://") || strings.ContainsAny(baseURL, "{}") || + egress.ValidatePublicHTTPSURL(ctx, baseURL) != nil { + return stack.Wrap(errors.New("base_url must be a public https URL without userinfo, query or fragment")) + } + return nil +} + // CustomManifest is the manifest a custom connector is stored as, or why it cannot be: one MCP // source at Endpoint, or one http source at BaseURL with Tools, and of the client only its // registration, auth_method and alg. Which schemes the deployment has and whether Endpoint or diff --git a/acceleration/internal/connectors/core/http_tools.go b/acceleration/internal/connectors/core/http_tools.go index 103ace24c0..87e7fb3a2d 100644 --- a/acceleration/internal/connectors/core/http_tools.go +++ b/acceleration/internal/connectors/core/http_tools.go @@ -57,10 +57,12 @@ const ( // OpenAI documents taking in one request. maxHTTPTools = 128 // maxHTTPToolDescription is the cap a custom connector's own description has - // (CustomConnectorRequest.Description, internal/api/connectors.go). + // (CustomConnectorRequest.Description, internal/api/connectors.go), on a tool's description + // and on each of its parameters'. maxHTTPToolDescription = 1000 // maxHTTPPath is the cap a custom connector's MCP endpoint URL has - // (CustomConnectorRequest.Endpoint, internal/api/connectors.go). + // (CustomConnectorRequest.Endpoint, internal/api/connectors.go), on a tool's path and on the + // http source's endpoint, its base URL. maxHTTPPath = 2048 // maxHTTPParameters is the cap an agent config has on its connector bindings and its // visible_tools (internal/api/configs.go). @@ -177,6 +179,9 @@ func checkHTTPSource(fail func(field, format string, args ...any), field string, if !slices.Contains(httpParameterTypes, tool.Parameters[name].Type) { fail(field+".type", "%q is not one of %v", tool.Parameters[name].Type, httpParameterTypes) } + if len(tool.Parameters[name].Description) > maxHTTPToolDescription { + fail(field+".description", "is over %d bytes", maxHTTPToolDescription) + } } } } diff --git a/acceleration/internal/connectors/core/http_tools_test.go b/acceleration/internal/connectors/core/http_tools_test.go index 7007ff7335..93a7755dad 100644 --- a/acceleration/internal/connectors/core/http_tools_test.go +++ b/acceleration/internal/connectors/core/http_tools_test.go @@ -90,6 +90,11 @@ func (s *HTTPSourceSuite) TestAValidHTTPSourceIsAccepted() { "a parameter merely holding method": withTool(func(t *HTTPTool) { t.Parameters["http_method_name"] = HTTPParameter{Type: "string"} }), "a header that is no override": withSource(func(r *SourceRule) { r.Headers = map[string]string{"X-Api-Version": "2"} }), "outbound true": withSource(func(r *SourceRule) { r.Outbound = new(true) }), + "a base_url of 2048 bytes": func() Manifest { + m := httpManifest(forecast()) + m.Endpoints[SourceKindHTTP] = "https://api.example.com/" + strings.Repeat("a", 2024) + return m + }(), "an mcp source with an override header": {ID: "example", Revision: 1, Name: "Example", Schemes: []string{"bearer"}, Endpoints: map[string]string{SourceKindMCP: "https://api.example.com/mcp"}, Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP, Headers: map[string]string{"X-HTTP-Method-Override": "POST"}}}}, @@ -149,7 +154,20 @@ func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { "a brace": {withTool(func(t *HTTPTool) { t.Parameters["a}b"] = HTTPParameter{Type: "string"} }), `"a}b" is not 1 to 64`}, "an empty name": {withTool(func(t *HTTPTool) { t.Parameters[""] = HTTPParameter{Type: "string"} }), `"" is not 1 to 64`}, "a name of 65": {withTool(func(t *HTTPTool) { t.Parameters[strings.Repeat("p", 65)] = HTTPParameter{Type: "string"} }), `is not 1 to 64`}, - "65 parameters": {withTool(func(t *HTTPTool) { t.Parameters = parameters(65) }), `http_tools[0].parameters: has 65 parameters, over 64`}, + "a parameter description over 1000": {withTool(func(t *HTTPTool) { + t.Parameters["days"] = HTTPParameter{Type: "integer", Description: strings.Repeat("d", 1001)} + }), `http_tools[0].parameters.days.description: is over 1000 bytes`}, + "a base_url of 2049": {func() Manifest { + m := httpManifest(forecast()) + m.Endpoints[SourceKindHTTP] = "https://api.example.com/" + strings.Repeat("a", 2025) + return m + }(), `endpoints.http: is over 2048 bytes`}, + "a base_url over 2048": {func() Manifest { + m := httpManifest(forecast()) + m.Endpoints[SourceKindHTTP] = "https://api.example.com/" + strings.Repeat("a", 2048) + return m + }(), `endpoints.http: is over 2048 bytes`}, + "65 parameters": {withTool(func(t *HTTPTool) { t.Parameters = parameters(65) }), `http_tools[0].parameters: has 65 parameters, over 64`}, "an override header": {withSource(func(r *SourceRule) { r.Headers = map[string]string{"x-HTTP-method-OVERRIDE": "POST"} }), `sources[0].headers.x-HTTP-method-OVERRIDE: names a method override`}, "read_only_tools": {withSource(func(r *SourceRule) { r.ReadOnlyTools = []string{"get_forecast"} }), `sources[0].read_only_tools: is not set on an http source`}, diff --git a/acceleration/internal/connectors/core/manifest.go b/acceleration/internal/connectors/core/manifest.go index cc5b0ab84e..503faae7fc 100644 --- a/acceleration/internal/connectors/core/manifest.go +++ b/acceleration/internal/connectors/core/manifest.go @@ -832,6 +832,10 @@ func (m Manifest) Validate() error { fail(field+".kind", "is http a second time: a manifest has at most one http source") } checkHTTPSource(fail, field, source) + // An import has no request schema to cap it (maxLength on CustomHTTPAPI.base_url). + if endpoint := m.Endpoints[source.Endpoint]; len(endpoint) > maxHTTPPath { + fail("endpoints."+source.Endpoint, "is over %d bytes", maxHTTPPath) + } } else if len(source.HTTPTools) > 0 { fail(field+".http_tools", "is set only on a source of kind %s", SourceKindHTTP) } diff --git a/acceleration/internal/connectors/sources/http/AGENTS.md b/acceleration/internal/connectors/sources/http/AGENTS.md index 59aaf29eb1..a0b35bc1a7 100644 --- a/acceleration/internal/connectors/sources/http/AGENTS.md +++ b/acceleration/internal/connectors/sources/http/AGENTS.md @@ -1,6 +1,6 @@ # internal/connectors/sources/http -The `core.ToolSource` for a connector whose manifest lists its own tools, registered as `http` (`Kind`, `core.SourceKindHTTP`), the name a manifest's `sources[].kind` gives it. Each tool in `sources[].http_tools` (`core.HTTPTool`, validated in `core/http_tools.go`) is one HTTP request to the source's endpoint. Callers, through `core.Registry.ToolSources` (`cmd/router/main.go`): `POST /v1/agents/connections/{id}/validate` (`Discover`, `internal/api/connection_tools.go`) and the session (`Open`, `internal/session/connector_tools.go`), whose dispatcher runs `Toolset.Call` and bounds it itself. No stored connector has kind `http` until the API takes one (AI-3676): an import refuses one too (`importableDefinition`, `internal/store/datamove.go`) until then. +The `core.ToolSource` for a connector whose manifest lists its own tools, registered as `http` (`Kind`, `core.SourceKindHTTP`), the name a manifest's `sources[].kind` gives it. Each tool in `sources[].http_tools` (`core.HTTPTool`, validated in `core/http_tools.go`) is one HTTP request to the source's endpoint. Callers, through `core.Registry.ToolSources` (`cmd/router/main.go`): `POST /v1/agents/connections/{id}/validate` (`Discover`, `internal/api/connection_tools.go`) and the session (`Open`, `internal/session/connector_tools.go`), whose dispatcher runs `Toolset.Call` and bounds it itself. A connector of kind `http` is stored by `POST /v1/agents/connectors` with an `http` block (`customManifest`, `internal/api/connectors.go`) or by an import (`importableDefinition`, `internal/store/datamove.go`), each only with a public https base URL (`egress.ValidatePublicHTTPSURL`). ## Flow diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 3ecd8cb0ed..513efe4bf7 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -779,6 +779,10 @@ func (t dataTable) selectRows(customerID string, secrets []string) (string, []an // is what lets a move be resumed after it was interrupted. func (s *Store) ImportRow(ctx context.Context, customerID, table string, row json.RawMessage) error { spec, _ := dataTableByName(table) + row, err := importableRow(ctx, customerID, table, row) + if err != nil { + return err + } var stale []string if err := s.importRow(ctx, s.sideOf(spec), customerID, table, row, &stale); err != nil { return err @@ -801,8 +805,26 @@ func (s *Store) sideOf(table dataTable) *bun.DB { var lineColumns = []string{"stream_trunk_id", "stream_route_id", "stream_app_pk", "stream_call_id", "stream_call_type", "attached_at", "config_id"} -// importRow writes one row of an export or of a change (ImportRow). It adds to stale the cached -// values the row was and is read through, for the caller to forget once the write has committed. +// importableRow is row as importRow writes it, or why it is not imported: a connector definition +// only as the API would store it (importableDefinition). Every caller runs it before importRow and +// outside any transaction, since checking a definition can resolve its base URL's host, and a slow +// resolver would hold applyChanges' transaction open as long as the request lasts. +func importableRow(ctx context.Context, customerID, table string, row json.RawMessage) (json.RawMessage, error) { + if table != "connector_definitions" { + return row, nil + } + // The built-in customer owns the built-in definitions every app shares, and an import + // never writes them: `router replicate` without --as hands over "" until a row names + // a customer. + if customerID == BuiltinCustomer { + return nil, fmt.Errorf("store: an import writes a connector definition under a customer, and none is known yet: %w (name the customer with --as)", ErrNotACustomConnector) + } + return importableDefinition(ctx, row) +} + +// importRow writes one row of an export or of a change (ImportRow), which importableRow has +// checked. It adds to stale the cached values the row was and is read through, for the caller to +// forget once the write has committed. func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table string, row json.RawMessage, stale *[]string) error { if slices.Contains(retiredTables, table) { return nil @@ -838,17 +860,6 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str return err } } - if table == "connector_definitions" { - // The built-in customer owns the built-in definitions every app shares, and an import - // never writes them: `router replicate` without --as hands over "" until a row names - // a customer. - if customerID == BuiltinCustomer { - return fmt.Errorf("store: an import writes a connector definition under a customer, and none is known yet: %w (name the customer with --as)", ErrNotACustomConnector) - } - if row, err = importableDefinition(row); err != nil { - return err - } - } shape, err := s.shapeOf(ctx, table) if err != nil { return err @@ -1650,8 +1661,9 @@ func boughtHere(relation string) string { // the API would have stored it, so no field this release does not read arrives for one that does. Every imported // definition is a custom one, since the customer is forced onto the row (identity) and importRow refuses an import with // no customer, and only the API's rules keep a custom manifest from naming the operator's client or anything else the -// router would trust a built-in with (core.Manifest.AsCustom). -func importableDefinition(row json.RawMessage) (json.RawMessage, error) { +// router would trust a built-in with (core.Manifest.AsCustom). An http one's base URL is checked as the API checks it +// (core.CheckBaseURL). +func importableDefinition(ctx context.Context, row json.RawMessage) (json.RawMessage, error) { // Read by exact column name, as the insert reads the row: a JSON decoder also matches a // key in another case, which the insert then leaves out. var fields map[string]json.RawMessage @@ -1670,16 +1682,17 @@ func importableDefinition(row json.RawMessage) (json.RawMessage, error) { return nil, invalidImport(fmt.Errorf("store: read the manifest of imported connector definition %q: %w", id, err)) } } + // Before AsCustom, whose rules would answer an http:// one in their own words: one answer for every base URL + // refused, as the API answers (an app imports its own export). + if core.HTTPSource(manifest.Sources) != nil { + if err := core.CheckBaseURL(ctx, manifest.Endpoints[core.SourceKindHTTP]); err != nil { + return nil, fmt.Errorf("store: imported connector definition %q: %w: %w", id, ErrNotACustomConnector, err) + } + } custom, err := manifest.AsCustom(id) if err != nil { return nil, fmt.Errorf("store: imported connector definition %q: %w: %w", id, ErrNotACustomConnector, err) } - // The http source runs a stored tool before the call-time checks of AI-3675 exist, and the - // API stores no http connector before AI-3676, so no import stores one either, even one the - // rules above let through. AI-3676 lifts this. - if core.HTTPSource(custom.Sources) != nil { - return nil, fmt.Errorf("store: imported connector definition %q: %w: an http connector cannot be imported yet", id, ErrNotACustomConnector) - } if fields["manifest"], err = json.Marshal(custom); err != nil { return nil, stack.Wrap(err) } @@ -1942,6 +1955,18 @@ func (s *Store) applyChanges(ctx context.Context, db *bun.DB, customerID string, if len(changes) == 0 { return nil } + // Before the transaction opens (importableRow). + changes = slices.Clone(changes) + for i, change := range changes { + if change.Op == ChangeDelete || !appPolicy(change) { + continue + } + payload, err := importableRow(ctx, customerID, change.Table, change.Payload) + if err != nil { + return err + } + changes[i].Payload = payload + } var stale []string err := db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { for _, change := range changes { diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 9016acbcf6..60744f0306 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -2417,21 +2417,74 @@ func (s *DataMoveSuite) TestAnImportedDefinitionWhoseServerIsNotHTTPSIsRefused() } // customWeather is a manifest the API stores for a custom http connector custom_weather: one -// read-only GET tool on an API taking a key. -const customWeather = `{"id": "custom_acme", "revision": 1, "name": "Weather", "endpoints": {"http": "https://api.weather.example/v1"}, +// read-only GET tool on an API taking a key, at a public IP literal, so checking it resolves nothing. +const customWeather = `{"id": "custom_acme", "revision": 1, "name": "Weather", "endpoints": {"http": "https://8.8.8.8/v1"}, "schemes": ["api_key"], "sources": [{"kind": "http", "endpoint": "http", "http_tools": [{"name": "get_forecast", "description": "The forecast for a city.", "method": "GET", "path": "/forecast/{city}", "read_only": true, "parameters": {"city": {"type": "string", "required": true}}}]}]}` -// TestAnImportedHTTPDefinitionIsRefused: a definition the API would store for an http connector -// is refused, and writes nothing, until AI-3676 lifts it (importableDefinition). -func (s *DataMoveSuite) TestAnImportedHTTPDefinitionIsRefused() { +// TestAnImportedHTTPDefinitionIsStored: a definition the API would store for an http connector +// is stored as the API stores it (AI-3676 lifts AI-3674's refusal). +func (s *DataMoveSuite) TestAnImportedHTTPDefinitionIsStored() { id, err := s.importDefinition(customWeather) + s.Require().NoError(err) + s.Equal(1, s.definitionsNamed(id)) + var stored string + s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, + "SELECT manifest FROM connector_definitions WHERE customer_id = 'moved' AND id = ?", id).Scan(&stored)) + s.JSONEq(strings.Replace(customWeather, `"id": "custom_acme"`, `"id": "`+id+`"`, 1), stored) +} + +// TestAnImportedHTTPDefinitionWhoseAPIIsPrivateIsRefused: an import checks the base URL as the +// API does (AI-3674 S1.5), and writes nothing. +func (s *DataMoveSuite) TestAnImportedHTTPDefinitionWhoseAPIIsPrivateIsRefused() { + id, err := s.importDefinition(strings.Replace(customWeather, "https://8.8.8.8/v1", "https://169.254.169.254/v1", 1)) + s.ErrorIs(err, ErrNotACustomConnector) - s.ErrorContains(err, "an http connector cannot be imported yet") + s.ErrorContains(err, "base_url must be a public https URL without userinfo, query or fragment") s.Zero(s.definitionsNamed(id)) } +// TestAChangesDefinitionsAreCheckedBeforeItsTransactionOpens: AI-3676 S1.3, checking a +// definition can resolve its base URL's host, so a change set's definitions are checked before +// its transaction opens, not row by row inside it. The first change names no table and fails +// only once inside the transaction; the definition after it is refused first. +func (s *DataMoveSuite) TestAChangesDefinitionsAreCheckedBeforeItsTransactionOpens() { + id := "custom_" + newID() + private := strings.Replace(strings.Replace(customWeather, "https://8.8.8.8/v1", "https://169.254.169.254/v1", 1), + `"id": "custom_acme"`, `"id": "`+id+`"`, 1) + + err := s.destination.ApplyChanges(s.ctx, "moved", []DataChange{ + {Table: "no_such_table", Op: ChangeInsert, Payload: json.RawMessage(`{}`)}, + {Table: "connector_definitions", Op: ChangeInsert, Payload: json.RawMessage(`{"id": "` + id + `", "revision": 1, + "name": "Weather", "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": ` + private + `}`)}, + }) + + s.ErrorIs(err, ErrNotACustomConnector) + s.ErrorContains(err, "base_url must be a public https URL without userinfo, query or fragment") + s.NotErrorIs(err, ErrInvalidImport) + s.Zero(s.definitionsNamed(id)) +} + +// TestAChangesDefinitionArrivesWithoutAFieldThisReleaseDoesNotRead: a change set's definition is +// stored as the API would store it, as an import's is: the check before the transaction hands +// its normalized row on (applyChanges). +func (s *DataMoveSuite) TestAChangesDefinitionArrivesWithoutAFieldThisReleaseDoesNotRead() { + id := "custom_" + newID() + manifest := strings.Replace(customManifestWith(`"later": {"env": "GOOGLE"}`), "custom_acme", id, 1) + + err := s.destination.ApplyChanges(s.ctx, "moved", []DataChange{{Table: "connector_definitions", Op: ChangeInsert, + Payload: json.RawMessage(`{"id": "` + id + `", "revision": 1, "name": "Acme", "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": ` + manifest + `}`)}}) + + s.Require().NoError(err) + var stored string + s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, + "SELECT manifest FROM connector_definitions WHERE customer_id = 'moved' AND id = ?", id).Scan(&stored)) + var manifestStored map[string]any + s.Require().NoError(json.Unmarshal([]byte(stored), &manifestStored)) + s.NotContains(manifestStored, "later") +} + // TestAnImportedHTTPDefinitionWhoseReadOnlyToolWritesIsRefused: the http tool rules // (core.Manifest.Validate) hold for an import as for the API. func (s *DataMoveSuite) TestAnImportedHTTPDefinitionWhoseReadOnlyToolWritesIsRefused() { diff --git a/acceleration/internal/store/datamove_unit_test.go b/acceleration/internal/store/datamove_unit_test.go index 2f7c9c610e..95b3d2822f 100644 --- a/acceleration/internal/store/datamove_unit_test.go +++ b/acceleration/internal/store/datamove_unit_test.go @@ -1,7 +1,9 @@ package store import ( + "context" "encoding/json" + "strings" "testing" "github.com/stretchr/testify/suite" @@ -17,25 +19,58 @@ func TestImportableDefinitionSuite(t *testing.T) { suite.Run(t, new(ImportableDefinitionSuite)) } -// AI-3674 R1.1: the http source would run an imported http connector's tools before AI-3675's -// call-time checks, so an import refuses one until AI-3676 lifts it. An MCP one is still stored. -func (s *ImportableDefinitionSuite) TestAnHTTPConnectorIsRefusedAndAnMCPOneKept() { - http := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"http": "https://api.crm.example"}, - "schemes": ["bearer"], "sources": [{"kind": "http", "endpoint": "http", - "http_tools": [{"name": "delete_item", "description": "Deletes an item.", "method": "DELETE", "path": "/items/{id}", - "parameters": {"id": {"type": "string", "required": true}}}]}]}` +// importedHTTP is a manifest the API stores for an http connector whose API is at a public IP literal, so checking it +// resolves nothing. +const importedHTTP = `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"http": "https://8.8.8.8/api"}, + "schemes": ["bearer"], "sources": [{"kind": "http", "endpoint": "http", + "http_tools": [{"name": "delete_item", "description": "Deletes an item.", "method": "DELETE", "path": "/items/{id}", + "parameters": {"id": {"type": "string", "required": true}}}]}]}` + +// AI-3676 lifts AI-3674's refusal: an http connector is imported as the API stores one, and an MCP one as before. +func (s *ImportableDefinitionSuite) TestAnHTTPConnectorAndAnMCPOneAreKept() { mcp := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"mcp": "https://mcp.crm.example/mcp"}, "schemes": ["bearer"], "sources": [{"kind": "mcp", "endpoint": "mcp"}]}` + // 2048 bytes, the cap itself: pins the cap as maxHTTPPath, not one under it. + atTheCap := strings.Replace(importedHTTP, "https://8.8.8.8/api", "https://8.8.8.8/"+strings.Repeat("a", 2032), 1) + for _, manifest := range []string{importedHTTP, mcp, atTheCap} { + row, err := importableDefinition(context.Background(), json.RawMessage(`{"id": "custom_crm", "manifest": `+manifest+`}`)) + + s.Require().NoError(err) + var kept map[string]json.RawMessage + s.Require().NoError(json.Unmarshal(row, &kept)) + s.JSONEq(manifest, string(kept["manifest"])) + } +} - _, err := importableDefinition(json.RawMessage(`{"id": "custom_crm", "manifest": ` + http + `}`)) +// AI-3674 S1.5: an import checks an http connector's base URL as the API does, with AC-7 of AI-3669's addresses, and +// answers each the same, so an import cannot tell a private address from one that does not resolve. +func (s *ImportableDefinitionSuite) TestAnHTTPConnectorWhoseAPIIsNotPublicIsRefused() { + for _, base := range []string{"https://127.0.0.1", "https://10.0.0.1", "https://169.254.169.254", "https://[::1]", + "https://router-probe.invalid", + // S1.2: refused by core's rules too, which would answer each in their own words. + "http://8.8.8.8/api", "HTTPS://8.8.8.8/api", "https://8.8.8.8/{x}", "https://8.8.8.8/" + strings.Repeat("a", 2048), + // 2049 bytes, one over the cap: pins the cap as maxHTTPPath, not maxHTTPPath+1. + "https://8.8.8.8/" + strings.Repeat("a", 2033)} { + manifest := strings.Replace(importedHTTP, "https://8.8.8.8/api", base, 1) - s.ErrorIs(err, ErrNotACustomConnector) - s.ErrorContains(err, "an http connector cannot be imported yet") + _, err := importableDefinition(context.Background(), json.RawMessage(`{"id": "custom_crm", "manifest": `+manifest+`}`)) + + s.ErrorIs(err, ErrNotACustomConnector, base) + s.EqualError(err, `store: imported connector definition "custom_crm": `+ErrNotACustomConnector.Error()+ + ": base_url must be a public https URL without userinfo, query or fragment", base) + } +} - row, err := importableDefinition(json.RawMessage(`{"id": "custom_crm", "manifest": ` + mcp + `}`)) +// AI-3676 S1.1: an import has no request body limit to keep an http connector small, so core's caps refuse what the +// API's schema would: a parameter's description over 1000 bytes and a base URL over 2048. +func (s *ImportableDefinitionSuite) TestAnOversizedHTTPConnectorIsRefused() { + for name, manifest := range map[string]string{ + "a 2 MiB parameter description": strings.Replace(importedHTTP, `"parameters": {"id": {"type": "string", "required": true}}`, + `"parameters": {"id": {"type": "string", "required": true}, "q": {"type": "string", "description": "`+strings.Repeat("x", 2<<20)+`"}}`, 1), + "a 4 KiB base_url": strings.Replace(importedHTTP, "https://8.8.8.8/api", "https://8.8.8.8/"+strings.Repeat("a", 4096), 1), + } { + _, err := importableDefinition(context.Background(), json.RawMessage(`{"id": "custom_crm", "manifest": `+manifest+`}`)) - s.Require().NoError(err) - var kept map[string]json.RawMessage - s.Require().NoError(json.Unmarshal(row, &kept)) - s.JSONEq(mcp, string(kept["manifest"])) + s.ErrorIs(err, ErrNotACustomConnector, name) + } } diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py index 5ff8328d83..5c24360be0 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py @@ -90,17 +90,17 @@ def sync_detailed( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Response[Connector | ErrorResponse]: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -126,17 +126,17 @@ def sync( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Connector | ErrorResponse | None: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -157,17 +157,17 @@ async def asyncio_detailed( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Response[Connector | ErrorResponse]: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -191,17 +191,17 @@ async def asyncio( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Connector | ErrorResponse | None: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py index eb282be23d..ebaafbca39 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py @@ -241,6 +241,12 @@ from .credit_entry_kind import CreditEntryKind from .credit_page import CreditPage from .custom_connector_request import CustomConnectorRequest +from .custom_http_parameter import CustomHTTPParameter +from .custom_http_parameter_type import CustomHTTPParameterType +from .custom_http_tool import CustomHTTPTool +from .custom_http_tool_method import CustomHTTPToolMethod +from .custom_http_tool_parameters import CustomHTTPToolParameters +from .custom_httpapi import CustomHTTPAPI from .custom_model import CustomModel from .custom_model_page import CustomModelPage from .custom_model_request import CustomModelRequest @@ -913,6 +919,12 @@ "CreditEntryKind", "CreditPage", "CustomConnectorRequest", + "CustomHTTPAPI", + "CustomHTTPParameter", + "CustomHTTPParameterType", + "CustomHTTPTool", + "CustomHTTPToolMethod", + "CustomHTTPToolParameters", "CustomModel", "CustomModelPage", "CustomModelRequest", diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py index bf23e5b0a3..49fc4f711d 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py @@ -10,6 +10,7 @@ if TYPE_CHECKING: from ..models.connector_client import ConnectorClient + from ..models.custom_httpapi import CustomHTTPAPI T = TypeVar("T", bound="CustomConnectorRequest") @@ -17,36 +18,36 @@ @_attrs_define class CustomConnectorRequest: - """A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. + """A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. Attributes: - endpoint (str): The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An - address on a private network, loopback or link-local is refused. id (str): Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. name (str): schemes (list[str] | None): How a connection may authenticate. Each must be a scheme this deployment has, except oauth2_client_credentials, which a custom connector cannot use: it needs a token endpoint a custom connector cannot set. + endpoint (str | Unset): The MCP server, over Streamable HTTP: a public https URL without userinfo, query or + fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. category (str | Unset): client (ConnectorClient | Unset): How the OAuth client a connection uses is registered, and how the client authenticates at the token endpoint. description (str | Unset): scopes (list[str] | None | Unset): The scopes a consent asks for, each an RFC 6749 scope token. + http (CustomHTTPAPI | Unset): An HTTP API a custom connector calls, and the tools it offers an agent. """ - endpoint: str id: str name: str schemes: list[str] | None + endpoint: str | Unset = UNSET category: str | Unset = UNSET client: ConnectorClient | Unset = UNSET description: str | Unset = UNSET scopes: list[str] | None | Unset = UNSET + http: CustomHTTPAPI | Unset = UNSET def to_dict(self) -> dict[str, Any]: - endpoint = self.endpoint - id = self.id name = self.name @@ -58,6 +59,8 @@ def to_dict(self) -> dict[str, Any]: else: schemes = self.schemes + endpoint = self.endpoint + category = self.category client: dict[str, Any] | Unset = UNSET @@ -75,16 +78,21 @@ def to_dict(self) -> dict[str, Any]: else: scopes = self.scopes + http: dict[str, Any] | Unset = UNSET + if not isinstance(self.http, Unset): + http = self.http.to_dict() + field_dict: dict[str, Any] = {} field_dict.update( { - "endpoint": endpoint, "id": id, "name": name, "schemes": schemes, } ) + if endpoint is not UNSET: + field_dict["endpoint"] = endpoint if category is not UNSET: field_dict["category"] = category if client is not UNSET: @@ -93,16 +101,17 @@ def to_dict(self) -> dict[str, Any]: field_dict["description"] = description if scopes is not UNSET: field_dict["scopes"] = scopes + if http is not UNSET: + field_dict["http"] = http return field_dict @classmethod def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: from ..models.connector_client import ConnectorClient + from ..models.custom_httpapi import CustomHTTPAPI d = dict(src_dict) - endpoint = d.pop("endpoint") - id = d.pop("id") name = d.pop("name") @@ -122,6 +131,8 @@ def _parse_schemes(data: object) -> list[str] | None: schemes = _parse_schemes(d.pop("schemes")) + endpoint = d.pop("endpoint", UNSET) + category = d.pop("category", UNSET) _client = d.pop("client", UNSET) @@ -150,15 +161,23 @@ def _parse_scopes(data: object) -> list[str] | None | Unset: scopes = _parse_scopes(d.pop("scopes", UNSET)) + _http = d.pop("http", UNSET) + http: CustomHTTPAPI | Unset + if isinstance(_http, Unset): + http = UNSET + else: + http = CustomHTTPAPI.from_dict(_http) + custom_connector_request = cls( - endpoint=endpoint, id=id, name=name, schemes=schemes, + endpoint=endpoint, category=category, client=client, description=description, scopes=scopes, + http=http, ) return custom_connector_request diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter.py new file mode 100644 index 0000000000..6e252c2561 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from typing_extensions import Self + +from ..models.custom_http_parameter_type import CustomHTTPParameterType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="CustomHTTPParameter") + + +@_attrs_define +class CustomHTTPParameter: + """One value the model gives an http tool. + + Attributes: + type_ (CustomHTTPParameterType): + description (str | Unset): + required (bool | Unset): The model must give it. A parameter in the path must be required. + """ + + type_: CustomHTTPParameterType + description: str | Unset = UNSET + required: bool | Unset = UNSET + + def to_dict(self) -> dict[str, Any]: + type_ = self.type_.value + + description = self.description + + required = self.required + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "type": type_, + } + ) + if description is not UNSET: + field_dict["description"] = description + if required is not UNSET: + field_dict["required"] = required + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + type_ = CustomHTTPParameterType._decode(d.pop("type")) + + description = d.pop("description", UNSET) + + required = d.pop("required", UNSET) + + custom_http_parameter = cls( + type_=type_, + description=description, + required=required, + ) + + return custom_http_parameter diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter_type.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter_type.py new file mode 100644 index 0000000000..2d82dc9ffa --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter_type.py @@ -0,0 +1,31 @@ +from enum import StrEnum + + +class CustomHTTPParameterType(StrEnum): + CUSTOM_HTTP_PARAMETER_TYPE_BOOLEAN = "boolean" + CUSTOM_HTTP_PARAMETER_TYPE_INTEGER = "integer" + CUSTOM_HTTP_PARAMETER_TYPE_NUMBER = "number" + CUSTOM_HTTP_PARAMETER_TYPE_STRING = "string" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def _decode(cls, value: object) -> "CustomHTTPParameterType": + """Reads the value from an answer. A string this client does not list yet is kept as a member of its own, + so an answer from a newer router still reads, and is written back as it came.""" + try: + return cls(value) + except ValueError: + if not isinstance(value, str): + raise + member = str.__new__(cls, value) + member._name_ = value + member._value_ = value + return member + + def __reduce_ex__(self, protocol: object) -> object: + """Pickles a member this client does not list through _decode, as Enum's own reduce would call cls(value).""" + if self._value_ in type(self)._value2member_map_: + return super().__reduce_ex__(protocol) + return type(self)._decode, (self._value_,) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool.py new file mode 100644 index 0000000000..b443982400 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from typing_extensions import Self + +from ..models.custom_http_tool_method import CustomHTTPToolMethod +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.custom_http_tool_parameters import CustomHTTPToolParameters + + +T = TypeVar("T", bound="CustomHTTPTool") + + +@_attrs_define +class CustomHTTPTool: + """One tool of an http connector: one request, whose method and path are fixed. + + Attributes: + description (str): What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + method (CustomHTTPToolMethod): + name (str): 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + path (str): Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of + that name, which must be required. + parameters (CustomHTTPToolParameters | Unset): The values the model gives, by name, up to 64. A parameter not in + the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a + method override, such as _method or X-HTTP-Method-Override, is refused. + read_only (bool | Unset): The tool only reads. Only a GET or HEAD tool may say so. + """ + + description: str + method: CustomHTTPToolMethod + name: str + path: str + parameters: CustomHTTPToolParameters | Unset = UNSET + read_only: bool | Unset = UNSET + + def to_dict(self) -> dict[str, Any]: + description = self.description + + method = self.method.value + + name = self.name + + path = self.path + + parameters: dict[str, Any] | Unset = UNSET + if not isinstance(self.parameters, Unset): + parameters = self.parameters.to_dict() + + read_only = self.read_only + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "description": description, + "method": method, + "name": name, + "path": path, + } + ) + if parameters is not UNSET: + field_dict["parameters"] = parameters + if read_only is not UNSET: + field_dict["read_only"] = read_only + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.custom_http_tool_parameters import CustomHTTPToolParameters + + d = dict(src_dict) + description = d.pop("description") + + method = CustomHTTPToolMethod._decode(d.pop("method")) + + name = d.pop("name") + + path = d.pop("path") + + _parameters = d.pop("parameters", UNSET) + parameters: CustomHTTPToolParameters | Unset + if isinstance(_parameters, Unset): + parameters = UNSET + else: + parameters = CustomHTTPToolParameters.from_dict(_parameters) + + read_only = d.pop("read_only", UNSET) + + custom_http_tool = cls( + description=description, + method=method, + name=name, + path=path, + parameters=parameters, + read_only=read_only, + ) + + return custom_http_tool diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_method.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_method.py new file mode 100644 index 0000000000..5c52e76f1f --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_method.py @@ -0,0 +1,33 @@ +from enum import StrEnum + + +class CustomHTTPToolMethod(StrEnum): + CUSTOM_HTTP_TOOL_METHOD_DELETE = "DELETE" + CUSTOM_HTTP_TOOL_METHOD_GET = "GET" + CUSTOM_HTTP_TOOL_METHOD_HEAD = "HEAD" + CUSTOM_HTTP_TOOL_METHOD_PATCH = "PATCH" + CUSTOM_HTTP_TOOL_METHOD_POST = "POST" + CUSTOM_HTTP_TOOL_METHOD_PUT = "PUT" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def _decode(cls, value: object) -> "CustomHTTPToolMethod": + """Reads the value from an answer. A string this client does not list yet is kept as a member of its own, + so an answer from a newer router still reads, and is written back as it came.""" + try: + return cls(value) + except ValueError: + if not isinstance(value, str): + raise + member = str.__new__(cls, value) + member._name_ = value + member._value_ = value + return member + + def __reduce_ex__(self, protocol: object) -> object: + """Pickles a member this client does not list through _decode, as Enum's own reduce would call cls(value).""" + if self._value_ in type(self)._value2member_map_: + return super().__reduce_ex__(protocol) + return type(self)._decode, (self._value_,) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_parameters.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_parameters.py new file mode 100644 index 0000000000..72fdb18565 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_parameters.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +if TYPE_CHECKING: + from ..models.custom_http_parameter import CustomHTTPParameter + + +T = TypeVar("T", bound="CustomHTTPToolParameters") + + +@_attrs_define +class CustomHTTPToolParameters: + """The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or + DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method- + Override, is refused. + + """ + + additional_properties: dict[str, CustomHTTPParameter] = _attrs_field( + init=False, factory=dict + ) + + def to_dict(self) -> dict[str, Any]: + + field_dict: dict[str, Any] = {} + for prop_name, prop in self.additional_properties.items(): + field_dict[prop_name] = prop.to_dict() + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.custom_http_parameter import CustomHTTPParameter + + d = dict(src_dict) + custom_http_tool_parameters = cls() + + additional_properties = {} + for prop_name, prop_dict in d.items(): + additional_property = CustomHTTPParameter.from_dict(prop_dict) + + additional_properties[prop_name] = additional_property + + custom_http_tool_parameters.additional_properties = additional_properties + return custom_http_tool_parameters + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> CustomHTTPParameter: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: CustomHTTPParameter) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_httpapi.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_httpapi.py new file mode 100644 index 0000000000..25dfaee1b0 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_httpapi.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from typing_extensions import Self + +if TYPE_CHECKING: + from ..models.custom_http_tool import CustomHTTPTool + + +T = TypeVar("T", bound="CustomHTTPAPI") + + +@_attrs_define +class CustomHTTPAPI: + """An HTTP API a custom connector calls, and the tools it offers an agent. + + Attributes: + base_url (str): The API the tools call, each at its path under it: a public https URL without userinfo, query or + fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + tools (list[CustomHTTPTool]): At least one and at most 128, each name once. + """ + + base_url: str + tools: list[CustomHTTPTool] + + def to_dict(self) -> dict[str, Any]: + base_url = self.base_url + + tools = [] + for tools_item_data in self.tools: + tools_item = tools_item_data.to_dict() + tools.append(tools_item) + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "base_url": base_url, + "tools": tools, + } + ) + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.custom_http_tool import CustomHTTPTool + + d = dict(src_dict) + base_url = d.pop("base_url") + + tools = [] + _tools = d.pop("tools") + for tools_item_data in _tools: + tools_item = CustomHTTPTool.from_dict(tools_item_data) + + tools.append(tools_item) + + custom_httpapi = cls( + base_url=base_url, + tools=tools, + ) + + return custom_httpapi diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs index 1b84fb7883..5de6188d4c 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -7008,7 +7008,7 @@ public System.Collections.Generic.IDictionary AdditionalProperti } /// - /// A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. + /// A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class CustomConnectorRequest @@ -7024,10 +7024,16 @@ public partial class CustomConnectorRequest public string? Description { get; set; } = default!; /// - /// The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. + /// The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. /// [System.Text.Json.Serialization.JsonPropertyName("endpoint")] - public string Endpoint { get; set; } = default!; + public string? Endpoint { get; set; } = default!; + + /// + /// An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. + /// + [System.Text.Json.Serialization.JsonPropertyName("http")] + public CustomHTTPAPI? Http { get; set; } = default!; /// /// Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. @@ -7052,6 +7058,96 @@ public partial class CustomConnectorRequest } + /// + /// An HTTP API a custom connector calls, and the tools it offers an agent. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class CustomHTTPAPI + { + + /// + /// The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + /// + [System.Text.Json.Serialization.JsonPropertyName("base_url")] + public string BaseUrl { get; set; } = default!; + + /// + /// At least one and at most 128, each name once. + /// + [System.Text.Json.Serialization.JsonPropertyName("tools")] + public System.Collections.Generic.List Tools { get; set; } = new System.Collections.Generic.List(); + + } + + /// + /// One value the model gives an http tool. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class CustomHTTPParameter + { + + [System.Text.Json.Serialization.JsonPropertyName("description")] + public string? Description { get; set; } = default!; + + /// + /// The model must give it. A parameter in the path must be required. + /// + [System.Text.Json.Serialization.JsonPropertyName("required")] + public bool? Required { get; set; } = default!; + + /// + /// One of `string`, `number`, `integer`, `boolean`. + /// + [System.Text.Json.Serialization.JsonPropertyName("type")] + public string Type { get; set; } = default!; + + } + + /// + /// One tool of an http connector: one request, whose method and path are fixed. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class CustomHTTPTool + { + + /// + /// What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + /// + [System.Text.Json.Serialization.JsonPropertyName("description")] + public string Description { get; set; } = default!; + + /// + /// One of `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`. + /// + [System.Text.Json.Serialization.JsonPropertyName("method")] + public string Method { get; set; } = default!; + + /// + /// 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + /// + [System.Text.Json.Serialization.JsonPropertyName("name")] + public string Name { get; set; } = default!; + + /// + /// The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + /// + [System.Text.Json.Serialization.JsonPropertyName("parameters")] + public System.Collections.Generic.Dictionary? Parameters { get; set; } = default!; + + /// + /// Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + /// + [System.Text.Json.Serialization.JsonPropertyName("path")] + public string Path { get; set; } = default!; + + /// + /// The tool only reads. Only a GET or HEAD tool may say so. + /// + [System.Text.Json.Serialization.JsonPropertyName("read_only")] + public bool? ReadOnly { get; set; } = default!; + + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class CustomModel { diff --git a/sdks/go/acceleration/enums_test.go b/sdks/go/acceleration/enums_test.go index 8f88fedd08..1375c5f195 100644 --- a/sdks/go/acceleration/enums_test.go +++ b/sdks/go/acceleration/enums_test.go @@ -24,3 +24,39 @@ func TestAgentLogSourceKeepsItsConstantNames(t *testing.T) { } } } + +// TestInvocationArgumentTypeKeepsItsConstantNames pins the names v0.5.1 released, which +// CustomHTTPParameterType's string, number and boolean would rename the same way. +func TestInvocationArgumentTypeKeepsItsConstantNames(t *testing.T) { + named := map[acceleration.InvocationArgumentType]string{ + acceleration.Array: "array", + acceleration.Boolean: "boolean", + acceleration.Null: "null", + acceleration.Number: "number", + acceleration.Object: "object", + acceleration.String: "string", + } + for constant, value := range named { + if string(constant) != value { + t.Errorf("%q is spelled %q", value, constant) + } + } +} + +// TestCustomHTTPToolMethodNamesItsConstants pins prefixed names for the http methods, so the +// next enum with GET or POST in it renames nothing callers already use. +func TestCustomHTTPToolMethodNamesItsConstants(t *testing.T) { + named := map[acceleration.CustomHTTPToolMethod]string{ + acceleration.CustomHTTPToolMethodGET: "GET", + acceleration.CustomHTTPToolMethodHEAD: "HEAD", + acceleration.CustomHTTPToolMethodPOST: "POST", + acceleration.CustomHTTPToolMethodPUT: "PUT", + acceleration.CustomHTTPToolMethodPATCH: "PATCH", + acceleration.CustomHTTPToolMethodDELETE: "DELETE", + } + for constant, value := range named { + if string(constant) != value { + t.Errorf("%q is spelled %q", value, constant) + } + } +} diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 282cd0efcd..1bb37481f3 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -1099,6 +1099,60 @@ func (e CreditEntryKind) Valid() bool { } } +// Defines values for CustomHTTPParameterType. +const ( + CustomHTTPParameterTypeBoolean CustomHTTPParameterType = "boolean" + CustomHTTPParameterTypeInteger CustomHTTPParameterType = "integer" + CustomHTTPParameterTypeNumber CustomHTTPParameterType = "number" + CustomHTTPParameterTypeString CustomHTTPParameterType = "string" +) + +// Valid indicates whether the value is a known member of the CustomHTTPParameterType enum. +func (e CustomHTTPParameterType) Valid() bool { + switch e { + case CustomHTTPParameterTypeBoolean: + return true + case CustomHTTPParameterTypeInteger: + return true + case CustomHTTPParameterTypeNumber: + return true + case CustomHTTPParameterTypeString: + return true + default: + return false + } +} + +// Defines values for CustomHTTPToolMethod. +const ( + CustomHTTPToolMethodDELETE CustomHTTPToolMethod = "DELETE" + CustomHTTPToolMethodGET CustomHTTPToolMethod = "GET" + CustomHTTPToolMethodHEAD CustomHTTPToolMethod = "HEAD" + CustomHTTPToolMethodPATCH CustomHTTPToolMethod = "PATCH" + CustomHTTPToolMethodPOST CustomHTTPToolMethod = "POST" + CustomHTTPToolMethodPUT CustomHTTPToolMethod = "PUT" +) + +// Valid indicates whether the value is a known member of the CustomHTTPToolMethod enum. +func (e CustomHTTPToolMethod) Valid() bool { + switch e { + case CustomHTTPToolMethodDELETE: + return true + case CustomHTTPToolMethodGET: + return true + case CustomHTTPToolMethodHEAD: + return true + case CustomHTTPToolMethodPATCH: + return true + case CustomHTTPToolMethodPOST: + return true + case CustomHTTPToolMethodPUT: + return true + default: + return false + } +} + // Defines values for CustomModelRequestTrainsOnData. const ( CustomModelRequestTrainsOnDataNo CustomModelRequestTrainsOnData = "no" @@ -6487,7 +6541,7 @@ type CreditPage struct { NextCursor *string `json:"next_cursor,omitempty"` } -// CustomConnectorRequest A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. +// CustomConnectorRequest A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. type CustomConnectorRequest struct { Category *string `json:"category,omitempty"` @@ -6495,8 +6549,11 @@ type CustomConnectorRequest struct { Client *ConnectorClient `json:"client,omitempty"` Description *string `json:"description,omitempty"` - // Endpoint The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. - Endpoint string `json:"endpoint"` + // Endpoint The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. + Endpoint *string `json:"endpoint,omitempty"` + + // Http An HTTP API a custom connector calls, and the tools it offers an agent. + Http *CustomHTTPAPI `json:"http,omitempty"` // Id Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. Id string `json:"id"` @@ -6509,6 +6566,49 @@ type CustomConnectorRequest struct { Scopes *[]string `json:"scopes,omitempty"` } +// CustomHTTPAPI An HTTP API a custom connector calls, and the tools it offers an agent. +type CustomHTTPAPI struct { + // BaseUrl The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + BaseUrl string `json:"base_url"` + + // Tools At least one and at most 128, each name once. + Tools []CustomHTTPTool `json:"tools"` +} + +// CustomHTTPParameter One value the model gives an http tool. +type CustomHTTPParameter struct { + Description *string `json:"description,omitempty"` + + // Required The model must give it. A parameter in the path must be required. + Required *bool `json:"required,omitempty"` + Type CustomHTTPParameterType `json:"type"` +} + +// CustomHTTPParameterType defines model for CustomHTTPParameter.Type. +type CustomHTTPParameterType string + +// CustomHTTPTool One tool of an http connector: one request, whose method and path are fixed. +type CustomHTTPTool struct { + // Description What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + Description string `json:"description"` + Method CustomHTTPToolMethod `json:"method"` + + // Name 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + Name string `json:"name"` + + // Parameters The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + Parameters *map[string]CustomHTTPParameter `json:"parameters,omitempty"` + + // Path Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + Path string `json:"path"` + + // ReadOnly The tool only reads. Only a GET or HEAD tool may say so. + ReadOnly *bool `json:"read_only,omitempty"` +} + +// CustomHTTPToolMethod defines model for CustomHTTPTool.Method. +type CustomHTTPToolMethod string + // CustomModel defines model for CustomModel. type CustomModel struct { BaseUrl string `json:"base_url"` @@ -14068,9 +14168,9 @@ type ClientInterface interface { // Corresponds with GET /v1/agents/connectors (the `ListConnectors` operationId). ListConnectors(ctx context.Context, params *ListConnectorsParams, reqEditors ...RequestEditorFn) (*http.Response, error) - // CreateConnectorWithBody Add a custom MCP connector + // CreateConnectorWithBody Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -14079,9 +14179,9 @@ type ClientInterface interface { // Corresponds with POST /v1/agents/connectors (the `CreateConnector` operationId). CreateConnectorWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - // CreateConnector Add a custom MCP connector + // CreateConnector Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -18234,9 +18334,9 @@ func (c *Client) ListConnectors(ctx context.Context, params *ListConnectorsParam return c.Client.Do(req) } -// CreateConnectorWithBody Add a custom MCP connector +// CreateConnectorWithBody Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -18255,9 +18355,9 @@ func (c *Client) CreateConnectorWithBody(ctx context.Context, contentType string return c.Client.Do(req) } -// CreateConnector Add a custom MCP connector +// CreateConnector Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -37353,9 +37453,9 @@ type ClientWithResponsesInterface interface { // Corresponds with GET /v1/agents/connectors (the `ListConnectors` operationId). ListConnectorsWithResponse(ctx context.Context, params *ListConnectorsParams, reqEditors ...RequestEditorFn) (*ListConnectorsResponse, error) - // CreateConnectorWithBodyWithResponse Add a custom MCP connector + // CreateConnectorWithBodyWithResponse Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -37364,9 +37464,9 @@ type ClientWithResponsesInterface interface { // Corresponds with POST /v1/agents/connectors (the `CreateConnector` operationId). CreateConnectorWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateConnectorResponse, error) - // CreateConnectorWithResponse Add a custom MCP connector + // CreateConnectorWithResponse Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -69143,9 +69243,9 @@ func (c *ClientWithResponses) ListConnectorsWithResponse(ctx context.Context, pa return ParseListConnectorsResponse(rsp) } -// CreateConnectorWithBodyWithResponse Add a custom MCP connector +// CreateConnectorWithBodyWithResponse Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -69160,9 +69260,9 @@ func (c *ClientWithResponses) CreateConnectorWithBodyWithResponse(ctx context.Co return ParseCreateConnectorResponse(rsp) } -// CreateConnectorWithResponse Add a custom MCP connector +// CreateConnectorWithResponse Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index 6d87e6bb5f..62b9a1f4a3 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -1130,8 +1130,8 @@ export type paths = { readonly get: operations["listConnectors"]; readonly put?: never; /** - * Add a custom MCP connector - * @description Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + * Add a custom connector + * @description Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. * * Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. */ @@ -7197,13 +7197,15 @@ export type components = { readonly items: readonly components["schemas"]["CreditEntry"][]; readonly next_cursor?: string; }; - /** @description A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. */ + /** @description A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. */ readonly CustomConnectorRequest: { readonly category?: string; readonly client?: components["schemas"]["ConnectorClient"]; readonly description?: string; - /** @description The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. */ - readonly endpoint: string; + /** @description The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. */ + readonly endpoint?: string; + /** @description An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. */ + readonly http?: components["schemas"]["CustomHTTPAPI"]; /** @description Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. */ readonly id: string; readonly name: string; @@ -7212,6 +7214,38 @@ export type components = { /** @description The scopes a consent asks for, each an RFC 6749 scope token. */ readonly scopes?: readonly string[] | null; }; + /** @description An HTTP API a custom connector calls, and the tools it offers an agent. */ + readonly CustomHTTPAPI: { + /** @description The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. */ + readonly base_url: string; + /** @description At least one and at most 128, each name once. */ + readonly tools: readonly components["schemas"]["CustomHTTPTool"][]; + }; + /** @description One value the model gives an http tool. */ + readonly CustomHTTPParameter: { + readonly description?: string; + /** @description The model must give it. A parameter in the path must be required. */ + readonly required?: boolean; + /** @enum {string} */ + readonly type: "string" | "number" | "integer" | "boolean"; + }; + /** @description One tool of an http connector: one request, whose method and path are fixed. */ + readonly CustomHTTPTool: { + /** @description What the tool does, which the model reads to know when to use it. Up to 1000 bytes. */ + readonly description: string; + /** @enum {string} */ + readonly method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE"; + /** @description 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. */ + readonly name: string; + /** @description The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. */ + readonly parameters?: { + readonly [key: string]: components["schemas"]["CustomHTTPParameter"]; + }; + /** @description Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. */ + readonly path: string; + /** @description The tool only reads. Only a GET or HEAD tool may say so. */ + readonly read_only?: boolean; + }; readonly CustomModel: { readonly base_url: string; /** Format: int64 */ diff --git a/sdks/php/src/Generated/CustomConnectorRequest.php b/sdks/php/src/Generated/CustomConnectorRequest.php index df5cac0e40..d3d86747cc 100644 --- a/sdks/php/src/Generated/CustomConnectorRequest.php +++ b/sdks/php/src/Generated/CustomConnectorRequest.php @@ -9,26 +9,28 @@ use GetStream\VisionAgents\Json; /** - * A custom MCP server for the app's agents to connect to. An unknown field is refused rather - * than ignored. + * A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is + * refused rather than ignored. */ final readonly class CustomConnectorRequest { public function __construct( - // The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on... - public string $endpoint, // Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id... public string $id, public string $name, // How a connection may authenticate. Each must be a scheme this deployment has, except oauth2_client_credenti... /** @var list */ public array $schemes, + // The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on... + public ?string $endpoint = null, public ?string $category = null, public ?ConnectorClient $client = null, public ?string $description = null, // The scopes a consent asks for, each an RFC 6749 scope token. /** @var list|null */ public ?array $scopes = null, + // An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. + public ?CustomHTTPAPI $http = null, ) { } @@ -38,14 +40,15 @@ public function __construct( public static function fromArray(array $data): self { return new self( - endpoint: Json::string($data, 'endpoint'), id: Json::string($data, 'id'), name: Json::string($data, 'name'), schemes: Json::strings($data, 'schemes'), + endpoint: array_key_exists('endpoint', $data) && $data['endpoint'] !== null ? Json::string($data, 'endpoint') : null, category: array_key_exists('category', $data) && $data['category'] !== null ? Json::string($data, 'category') : null, client: array_key_exists('client', $data) && $data['client'] !== null ? ConnectorClient::fromArray(Json::object($data, 'client')) : null, description: array_key_exists('description', $data) && $data['description'] !== null ? Json::string($data, 'description') : null, scopes: array_key_exists('scopes', $data) && $data['scopes'] !== null ? Json::strings($data, 'scopes') : null, + http: array_key_exists('http', $data) && $data['http'] !== null ? CustomHTTPAPI::fromArray(Json::object($data, 'http')) : null, ); } @@ -57,10 +60,12 @@ public static function fromArray(array $data): self public function toArray(): array { $out = []; - $out['endpoint'] = $this->endpoint; $out['id'] = $this->id; $out['name'] = $this->name; $out['schemes'] = $this->schemes; + if ($this->endpoint !== null) { + $out['endpoint'] = $this->endpoint; + } if ($this->category !== null) { $out['category'] = $this->category; } @@ -73,6 +78,9 @@ public function toArray(): array if ($this->scopes !== null) { $out['scopes'] = $this->scopes; } + if ($this->http !== null) { + $out['http'] = $this->http->toArray(); + } return $out; } } diff --git a/sdks/php/src/Generated/CustomHTTPAPI.php b/sdks/php/src/Generated/CustomHTTPAPI.php new file mode 100644 index 0000000000..83a4e3c8a6 --- /dev/null +++ b/sdks/php/src/Generated/CustomHTTPAPI.php @@ -0,0 +1,48 @@ + */ + public array $tools, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + baseUrl: Json::string($data, 'base_url'), + tools: array_map(CustomHTTPTool::fromArray(...), Json::objects($data, 'tools')), + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['base_url'] = $this->baseUrl; + $out['tools'] = array_map(static fn (CustomHTTPTool $each): array => $each->toArray(), $this->tools); + return $out; + } +} diff --git a/sdks/php/src/Generated/CustomHTTPParameter.php b/sdks/php/src/Generated/CustomHTTPParameter.php new file mode 100644 index 0000000000..bbb34335b8 --- /dev/null +++ b/sdks/php/src/Generated/CustomHTTPParameter.php @@ -0,0 +1,53 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self( + type: Json::string($data, 'type'), + description: array_key_exists('description', $data) && $data['description'] !== null ? Json::string($data, 'description') : null, + required: array_key_exists('required', $data) && $data['required'] !== null ? Json::bool($data, 'required') : null, + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['type'] = $this->type; + if ($this->description !== null) { + $out['description'] = $this->description; + } + if ($this->required !== null) { + $out['required'] = $this->required; + } + return $out; + } +} diff --git a/sdks/php/src/Generated/CustomHTTPTool.php b/sdks/php/src/Generated/CustomHTTPTool.php new file mode 100644 index 0000000000..905a47b4d7 --- /dev/null +++ b/sdks/php/src/Generated/CustomHTTPTool.php @@ -0,0 +1,67 @@ +|null */ + public ?array $parameters = null, + // The tool only reads. Only a GET or HEAD tool may say so. + public ?bool $readOnly = null, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + description: Json::string($data, 'description'), + method: Json::string($data, 'method'), + name: Json::string($data, 'name'), + path: Json::string($data, 'path'), + parameters: array_key_exists('parameters', $data) && $data['parameters'] !== null ? Json::object($data, 'parameters') : null, + readOnly: array_key_exists('read_only', $data) && $data['read_only'] !== null ? Json::bool($data, 'read_only') : null, + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['description'] = $this->description; + $out['method'] = $this->method; + $out['name'] = $this->name; + $out['path'] = $this->path; + if ($this->parameters !== null) { + $out['parameters'] = Json::objectValue($this->parameters); + } + if ($this->readOnly !== null) { + $out['read_only'] = $this->readOnly; + } + return $out; + } +} diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb index 2496d3a998..774477ff1b 100644 --- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb +++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb @@ -2432,8 +2432,20 @@ module Generated required: %w[items has_more].freeze, open: false }.freeze, "CustomConnectorRequest" => { - properties: %w[category client description endpoint id name schemes scopes].freeze, - required: %w[id name endpoint schemes].freeze, open: false + properties: %w[category client description endpoint http id name schemes scopes].freeze, + required: %w[id name schemes].freeze, open: false + }.freeze, + "CustomHTTPAPI" => { + properties: %w[base_url tools].freeze, + required: %w[base_url tools].freeze, open: false + }.freeze, + "CustomHTTPParameter" => { + properties: %w[description required type].freeze, + required: %w[type].freeze, open: false + }.freeze, + "CustomHTTPTool" => { + properties: %w[description method name parameters path read_only].freeze, + required: %w[name description method path].freeze, open: false }.freeze, "CustomModel" => { properties: %w[base_url context_window created_at has_api_key id input_modalities model name per_million_input_tokens per_million_output_tokens retention target trains_on_data updated_at].freeze, diff --git a/sdks/rust/src/operations.rs b/sdks/rust/src/operations.rs index 5432840eb2..7e7f753f9b 100644 --- a/sdks/rust/src/operations.rs +++ b/sdks/rust/src/operations.rs @@ -951,7 +951,7 @@ impl Client { ) .await } - /// Add a custom MCP connector + /// Add a custom connector /// /// `POST /v1/agents/connectors` (`createConnector`). pub async fn create_connector( diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs index b90d80196e..50c1760691 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -5275,7 +5275,7 @@ pub struct CreditPage { #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub next_cursor: ::std::option::Option<::std::string::String>, } -///A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. +///A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] #[serde(deny_unknown_fields)] #[derive(Default)] @@ -5286,8 +5286,12 @@ pub struct CustomConnectorRequest { pub client: ::std::option::Option, #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub description: ::std::option::Option<::std::string::String>, - ///The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. - pub endpoint: ::std::string::String, + ///The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub endpoint: ::std::option::Option<::std::string::String>, + ///An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub http: ::std::option::Option, ///Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. pub id: ::std::string::String, pub name: ::std::string::String, @@ -5298,6 +5302,165 @@ pub struct CustomConnectorRequest { #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub scopes: ::std::option::Option<::std::vec::Vec<::std::string::String>>, } +///One value the model gives an http tool. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct CustomHttpParameter { + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option<::std::string::String>, + ///The model must give it. A parameter in the path must be required. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub required: ::std::option::Option, + #[serde(rename = "type")] + pub type_: CustomHttpParameterType, +} +///`CustomHttpParameterType` +#[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, +)] +pub enum CustomHttpParameterType { + #[serde(rename = "string")] + String, + #[serde(rename = "number")] + Number, + #[serde(rename = "integer")] + Integer, + #[serde(rename = "boolean")] + Boolean, + /// A value this SDK's spec does not list, as the router sent it. + #[serde(untagged)] + Unlisted(::std::string::String), +} +impl ::std::fmt::Display for CustomHttpParameterType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::String => f.write_str("string"), + Self::Number => f.write_str("number"), + Self::Integer => f.write_str("integer"), + Self::Boolean => f.write_str("boolean"), + Self::Unlisted(ref value) => f.write_str(value), + } + } +} +impl ::std::str::FromStr for CustomHttpParameterType { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "string" => Ok(Self::String), + "number" => Ok(Self::Number), + "integer" => Ok(Self::Integer), + "boolean" => Ok(Self::Boolean), + _ => Err("invalid value".into()), + } + } +} +impl ::std::convert::TryFrom<&str> for CustomHttpParameterType { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } +} +impl ::std::convert::TryFrom<::std::string::String> for CustomHttpParameterType { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } +} +///One tool of an http connector: one request, whose method and path are fixed. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct CustomHttpTool { + ///What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + pub description: ::std::string::String, + pub method: CustomHttpToolMethod, + ///1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + pub name: ::std::string::String, + ///The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + #[serde( + default, + skip_serializing_if = ":: std :: collections :: BTreeMap::is_empty" + )] + pub parameters: ::std::collections::BTreeMap<::std::string::String, CustomHttpParameter>, + ///Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + pub path: ::std::string::String, + ///The tool only reads. Only a GET or HEAD tool may say so. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub read_only: ::std::option::Option, +} +///`CustomHttpToolMethod` +#[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, +)] +pub enum CustomHttpToolMethod { + #[serde(rename = "GET")] + Get, + #[serde(rename = "HEAD")] + Head, + #[serde(rename = "POST")] + Post, + #[serde(rename = "PUT")] + Put, + #[serde(rename = "PATCH")] + Patch, + #[serde(rename = "DELETE")] + Delete, + /// A value this SDK's spec does not list, as the router sent it. + #[serde(untagged)] + Unlisted(::std::string::String), +} +impl ::std::fmt::Display for CustomHttpToolMethod { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Get => f.write_str("GET"), + Self::Head => f.write_str("HEAD"), + Self::Post => f.write_str("POST"), + Self::Put => f.write_str("PUT"), + Self::Patch => f.write_str("PATCH"), + Self::Delete => f.write_str("DELETE"), + Self::Unlisted(ref value) => f.write_str(value), + } + } +} +impl ::std::str::FromStr for CustomHttpToolMethod { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "GET" => Ok(Self::Get), + "HEAD" => Ok(Self::Head), + "POST" => Ok(Self::Post), + "PUT" => Ok(Self::Put), + "PATCH" => Ok(Self::Patch), + "DELETE" => Ok(Self::Delete), + _ => Err("invalid value".into()), + } + } +} +impl ::std::convert::TryFrom<&str> for CustomHttpToolMethod { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } +} +impl ::std::convert::TryFrom<::std::string::String> for CustomHttpToolMethod { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } +} +///An HTTP API a custom connector calls, and the tools it offers an agent. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +#[derive(Default)] +pub struct CustomHttpapi { + ///The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + pub base_url: ::std::string::String, + ///At least one and at most 128, each name once. + pub tools: ::std::vec::Vec, +} ///`CustomModel` #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] pub struct CustomModel { From c72f50fbd0cf85cabe0169ee0798d74ae09ff188 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 16:16:11 +0100 Subject: [PATCH 05/13] [AI-3871] A connector's answer names its source kind (#2464) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Targets the feature branch `feature/ai-3669-http-connectors`, not `main`. Fix leaf of AI-3669 (umbrella AI-3870). ## Why With http connectors stored, `GET /v1/agents/connectors[/{id}]` answered a `Connector` with no source kind, so the CLI could not tell an http custom connector from an MCP one. The cli#128 review showed it: `agents mcp list` lists http connectors as MCP servers, and `agents mcp update ` with no local file turned an http connector into an MCP one. The CLI already decodes `sources: [{kind}]` (GetStream/cli `internal/agents/connectors.go:21`); this makes the router answer it. ## How it works ``` Connector (GET /v1/agents/connectors, /{id}, the create's answer) └─ sources: one entry per manifest source, in order, kind only ├─ custom, made from `endpoint` -> [{"kind":"mcp"}] ├─ custom, made from `http` -> [{"kind":"http"}] ├─ built-in -> its own kinds (slack: [{"kind":"mcp"}]) └─ never a URL, base_url, path, headers or tool ``` `kind` is the named enum `ConnectorSourceKind` (`mcp` | `http`), with `x-enum-varnames` so the Go SDK gets `ConnectorSourceKindMCP` and `ConnectorSourceKindHTTP` and a later enum holding `mcp` or `http` renames nothing (as #2344 did for `CustomHTTPToolMethod`). `sources` is always an array, `nullable: false`. ## Changes | Change | Test that proves it | | --- | --- | | `Connector.sources` built from `manifest.Sources` by kind (`connectors.go` `connectorOf`) | `TestConnectorSourcesSuite` (order, empty list is `[]`, nothing but kind); `TestAConnectorShowsItsSourceKindAndNoAddress` (create, read, list of an http and an MCP custom connector, and slack; no `base_url`, `endpoint`, address, path or tool name in the answer) | | Two controls that listed the keys of a connector answer gain `sources` | `TestAnMCPConnectorIsAnsweredAsBefore`, `TestABuiltInReadsAsBeforeOnARouterWithoutAPublicURL`; `TestWhatTheRouterReadsToConnectIsNeverShown` no longer withholds `sources` but asserts it is `[{kind: mcp}]` | | `openapi.yaml` and the clients regenerated | Go, JS, Python (`plugins/stream`), .NET, Ruby, Rust and PHP changed; Kotlin, Swift and Dart checked, unchanged (`Connector` is not client-accessible) | | Go constant names pinned | `TestConnectorSourceKindNamesItsConstants` (`sdks/go/acceleration/enums_test.go`) | | SDK note appended | `.claude/skills/sdk/notes/2026-11-24-ai-3676.md` | ## Validation - `go test ./internal/api/` (unit) and, on my own test DB, `go test -tags integration -run 'TestConnectorsSuite|TestAuthorizationsSuite|TestConnectionsSuite|TestConnectionProxySuite|TestConnectorProviderAppsSuite|TestConnectorEventsSuite|TestDataMoveSuite|TestOAuthClientsSuite|TestConfigsSuite' ./internal/api/` pass; `go vet` with and without `-tags integration` clean; `go test ./acceleration/` in `sdks/go` passes. - Mutations: loop body dropped, kind hardcoded, nil instead of empty list, endpoint appended to the kind, reversed order (each killed by `TestConnectorSourcesSuite`); enum value dropped, varnames dropped, `nullable:"false"` dropped (each killed by `TestPostureSuite`, the spec check; the varnames one also fails `enums_test.go` after `go generate`). - Not run here: the full integration run, Swift/Kotlin/Dart tests, the CLI side (cli#128). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Sonnet 5.5 --- .../skills/sdk/notes/2026-11-24-ai-3676.md | 2 + acceleration/api/openapi.yaml | 24 ++++++++ acceleration/internal/api/connectors.go | 42 +++++++++++-- .../internal/api/connectors_sources_test.go | 56 +++++++++++++++++ acceleration/internal/api/connectors_test.go | 61 ++++++++++++++++--- .../stream/_generated/models/__init__.py | 4 ++ .../stream/_generated/models/connector.py | 20 ++++++ .../_generated/models/connector_source.py | 47 ++++++++++++++ .../models/connector_source_kind.py | 29 +++++++++ .../Generated/Models.cs | 18 ++++++ sdks/go/acceleration/enums_test.go | 14 +++++ sdks/go/acceleration/generated.go | 30 +++++++++ sdks/js/src/generated/api.ts | 11 ++++ sdks/php/src/Generated/Connector.php | 5 ++ sdks/php/src/Generated/ConnectorSource.php | 42 +++++++++++++ .../php/src/Generated/ConnectorSourceKind.php | 16 +++++ .../getstream/vision_agents/generated/spec.rb | 8 ++- sdks/rust/src/types.rs | 54 ++++++++++++++++ 18 files changed, 469 insertions(+), 14 deletions(-) create mode 100644 acceleration/internal/api/connectors_sources_test.go create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source.py create mode 100644 plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source_kind.py create mode 100644 sdks/php/src/Generated/ConnectorSource.php create mode 100644 sdks/php/src/Generated/ConnectorSourceKind.php diff --git a/.claude/skills/sdk/notes/2026-11-24-ai-3676.md b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md index 75c3fcf685..a3f9cf816f 100644 --- a/.claude/skills/sdk/notes/2026-11-24-ai-3676.md +++ b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md @@ -1 +1,3 @@ `createConnector` (`POST /v1/agents/connectors`) takes an HTTP API in place of an MCP server (AI-3676). `CustomConnectorRequest` has a new optional `http`, a `CustomHTTPAPI` `{base_url, tools}`. Each tool is a `CustomHTTPTool` `{name, description, method, path, parameters, read_only}`: `method` is one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH` and `DELETE`, and `parameters` maps a name to a `CustomHTTPParameter` `{type, description, required}`, whose `type` is one of `string`, `number`, `integer` and `boolean`. `endpoint` is no longer required: a request sends a non-empty `endpoint` or `http`, not both. This breaks existing callers in four SDKs. In Go, `CustomConnectorRequest.Endpoint` is now a `*string` (`sdks/go/acceleration/generated.go`), and a caller that set it as a string now sets a pointer. In Rust, `CustomConnectorRequest.endpoint` is now an `Option` (`sdks/rust/src/types.rs`), so a struct literal or a read of a `String` no longer compiles. In PHP (`sdks/php/src/Generated/CustomConnectorRequest.php`) and Python (`plugins/stream`, `_generated/models/custom_connector_request.py`), `endpoint` moves from the first constructor argument to after `schemes`, so a positional call no longer matches; named and keyword arguments still work. The `Connector` the router answers is unchanged, so it shows neither `base_url` nor the tools. Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients. Other SDKs need to update: a `connectors.create` resource method, where an SDK has one, takes `http` beside `endpoint`. Swift, Kotlin and Dart need nothing, since `createConnector` is not client-accessible. + +The `Connector` the router answers now has `sources` (AI-3871), a list of `ConnectorSource` `{kind}` whose `kind` is `mcp` or `http`: a custom connector made from an `endpoint` reads `mcp`, one made from `http` reads `http`, and a built-in names its own. It never carries a URL, a path or a tool. This adds a required field to a response, so a client that builds a `Connector` itself, or compares one whole, must give it `sources`. In Go it is `[]ConnectorSource`, and the constants are `ConnectorSourceKindMCP` and `ConnectorSourceKindHTTP`. Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients; Swift, Kotlin and Dart generate nothing new. Other SDKs need to update: a resource method that returns a connector (`connectors.get`, `connectors.list`), where an SDK has one, exposes `sources`, so a caller can tell an http connector from an MCP one. diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index dee76c8a56..96b3e5bbef 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -3552,6 +3552,11 @@ components: setup: $ref: '#/components/schemas/ConnectorSetup' description: What a person does at the provider before the first consent, such as registering an OAuth client. Absent when the manifest says nothing. + sources: + description: 'How the connector''s tools are reached, one entry per source, by kind only: never a URL, a path or a credential. A custom connector made from an endpoint is mcp, one made from http is http.' + items: + $ref: '#/components/schemas/ConnectorSource' + type: array sync_hash: description: The fingerprint of the file the CLI last synced onto this connector. Absent on a built-in, and on a connector that was never synced or was written since by anything that is not a sync. readOnly: true @@ -3564,6 +3569,7 @@ components: - schemes - inputs - scopes + - sources - client - channel - created_at @@ -4055,6 +4061,24 @@ components: - title - description type: object + ConnectorSource: + additionalProperties: false + description: One way a connector's tools are reached. Only its kind is shown. + properties: + kind: + $ref: '#/components/schemas/ConnectorSourceKind' + required: + - kind + type: object + ConnectorSourceKind: + description: mcp is an MCP server that lists the tools, http an HTTP API whose tools the manifest lists. + enum: + - mcp + - http + type: string + x-enum-varnames: + - ConnectorSourceKindMCP + - ConnectorSourceKindHTTP ConnectorToolGrant: description: One tool a binding allows. properties: diff --git a/acceleration/internal/api/connectors.go b/acceleration/internal/api/connectors.go index f99b2047fb..80346f4876 100644 --- a/acceleration/internal/api/connectors.go +++ b/acceleration/internal/api/connectors.go @@ -32,10 +32,11 @@ const usesNamed = 10 // Connector is one connector as the catalog shows it and a connection is created from: the // revision of its definition (store.ConnectorDefinition) the request read. It is the // non-secret part of the manifest: what a caller chooses between (schemes, inputs, scopes, -// who owns the OAuth client). Everything the router reads to connect is left out: a built-in's -// endpoints, vars, authorize and token parameters, capture and identity rules, refresh and -// rate limits, sources, hooks and the operator's client variables. A custom connector's -// endpoint is left out too: an MCP URL can carry a secret in its path (AI-837). +// who owns the OAuth client, how it is reached). Everything the router reads to connect is left +// out: a built-in's endpoints, vars, authorize and token parameters, capture and identity rules, +// refresh and rate limits, the sources' endpoints, headers and tools, hooks and the operator's +// client variables. A custom connector's endpoint is left out too: an MCP URL can carry a +// secret in its path (AI-837), and an http API's base URL can. type Connector struct { ID string `json:"id" doc:"Unique among the built-ins and the app's own. A custom definition's starts with custom_, and a built-in's never does."` Revision int `json:"revision" readOnly:"true" doc:"The manifest's revision. A connection is created from the newest one and keeps reading it until it is reconnected."` @@ -46,6 +47,7 @@ type Connector struct { Schemes []string `json:"schemes" doc:"How a connection may authenticate, such as oauth2_code."` Inputs []ConnectorInput `json:"inputs" doc:"What a connection is created with, such as a region or a shop."` Scopes []string `json:"scopes" doc:"The scopes a consent asks for."` + Sources []ConnectorSource `json:"sources" nullable:"false" doc:"How the connector's tools are reached, one entry per source, by kind only: never a URL, a path or a credential. A custom connector made from an endpoint is mcp, one made from http is http."` Client ConnectorClient `json:"client"` Setup *ConnectorSetup `json:"setup,omitempty" doc:"What a person does at the provider before the first consent, such as registering an OAuth client. Absent when the manifest says nothing."` RedirectURI string `json:"redirect_uri,omitempty" readOnly:"true" format:"uri" doc:"The redirect URI an OAuth client registered for this connector has to list: where every consent of this deployment sends the browser back to, ROUTER_PUBLIC_URL followed by /v1/agents/connectors/oauth/callback. Only on a connector that connects with oauth2_code, and absent when ROUTER_PUBLIC_URL is not set, since no consent can start then."` @@ -55,6 +57,33 @@ type Connector struct { CreatedAt time.Time `json:"created_at" readOnly:"true" doc:"When this revision was stored."` } +// ConnectorSource is one source of a connector's tools, as the catalog shows it. +type ConnectorSource struct { + Kind ConnectorSourceKind `json:"kind"` +} + +func (*ConnectorSource) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One way a connector's tools are reached. Only its kind is shown." + schema.AdditionalProperties = false + return schema +} + +// ConnectorSourceKind is how a source reaches a connector's tools (core.SourceKindMCP and +// core.SourceKindHTTP). +type ConnectorSourceKind string + +func (ConnectorSourceKind) Schema(registry huma.Registry) *huma.Schema { + ref := namedEnum(registry, "ConnectorSourceKind", + "mcp is an MCP server that lists the tools, http an HTTP API whose tools the manifest lists.", + core.SourceKindMCP, core.SourceKindHTTP) + // Named, so a later enum with mcp or http in it renames nothing in the Go SDK, as + // ConnectionOwnerType's constants are. + registry.Map()["ConnectorSourceKind"].Extensions = map[string]any{ + "x-enum-varnames": []string{"ConnectorSourceKindMCP", "ConnectorSourceKindHTTP"}, + } + return ref +} + // ConnectorSandbox is the manifest's sandbox block as the catalog shows it. type ConnectorSandbox struct { Env string `json:"env" doc:"The env var code in the sandbox reads, such as GITHUB_TOKEN. Its value is a placeholder: the sandbox's egress puts the connection's credential in its place, only in a request header and only to one of hosts."` @@ -563,6 +592,10 @@ func connectorOf(definition store.ConnectorDefinition, publicURL string) Connect if slices.Contains(manifest.Schemes, oauth2code.Name) { redirectURI = connectorCallbackURL(publicURL) } + sources := make([]ConnectorSource, 0, len(manifest.Sources)) + for _, source := range manifest.Sources { + sources = append(sources, ConnectorSource{Kind: ConnectorSourceKind(source.Kind)}) + } var sandbox *ConnectorSandbox if manifest.Sandbox != nil { sandbox = &ConnectorSandbox{Env: manifest.Sandbox.Env, Hosts: slices.Clone(manifest.Sandbox.Hosts)} @@ -581,6 +614,7 @@ func connectorOf(definition store.ConnectorDefinition, publicURL string) Connect Schemes: append([]string{}, manifest.Schemes...), Inputs: inputs, Scopes: append([]string{}, manifest.Scopes.List...), + Sources: sources, Client: ConnectorClient{ Registration: registrations, AuthMethod: ConnectorClientAuthMethod(manifest.Client.AuthMethod), diff --git a/acceleration/internal/api/connectors_sources_test.go b/acceleration/internal/api/connectors_sources_test.go new file mode 100644 index 0000000000..77889dcda4 --- /dev/null +++ b/acceleration/internal/api/connectors_sources_test.go @@ -0,0 +1,56 @@ +package api + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/suite" + + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + "github.com/GetStream/Vision-Agents/acceleration/internal/store" +) + +// ConnectorSourcesSuite covers the sources a Connector shows, without a store. +type ConnectorSourcesSuite struct { + suite.Suite +} + +func TestConnectorSourcesSuite(t *testing.T) { + suite.Run(t, new(ConnectorSourcesSuite)) +} + +// sourcesJSON is what a caller reads of the sources of a manifest with these source rules. +func (s *ConnectorSourcesSuite) sourcesJSON(rules ...core.SourceRule) string { + shown := connectorOf(store.ConnectorDefinition{Manifest: core.Manifest{Sources: rules}}, "") + raw, err := json.Marshal(shown) + s.Require().NoError(err) + var decoded struct { + Sources json.RawMessage `json:"sources"` + } + s.Require().NoError(json.Unmarshal(raw, &decoded)) + return string(decoded.Sources) +} + +// Defect: one entry per kind rather than per source, or the order lost, so a connector with an +// http source beside its mcp one reads as only one of them. +func (s *ConnectorSourcesSuite) TestEverySourceIsShownByItsKindInTheManifestsOrder() { + s.JSONEq(`[{"kind":"mcp"},{"kind":"http"}]`, s.sourcesJSON( + core.SourceRule{Kind: core.SourceKindMCP, Endpoint: "mcp"}, core.SourceRule{Kind: core.SourceKindHTTP, Endpoint: "http"})) + s.JSONEq(`[{"kind":"http"},{"kind":"mcp"}]`, s.sourcesJSON( + core.SourceRule{Kind: core.SourceKindHTTP, Endpoint: "http"}, core.SourceRule{Kind: core.SourceKindMCP, Endpoint: "mcp"})) +} + +// Defect: a connector with no source answering null, which a client reads as absent. +func (s *ConnectorSourcesSuite) TestAConnectorWithNoSourceShowsAnEmptyList() { + s.Equal(`[]`, s.sourcesJSON()) +} + +// Defect: a source's endpoint, headers or tools copied into the answer with its kind. +func (s *ConnectorSourcesSuite) TestASourceShowsNothingButItsKind() { + rule := core.SourceRule{ + Kind: core.SourceKindHTTP, Endpoint: "http", Headers: map[string]string{"X-Team": "secret-team"}, + Tools: []core.ToolRule{{Name: "scoped", NeedsScopes: []string{"s"}}}, + HTTPTools: []core.HTTPTool{{Name: "get_forecast", Method: "GET", Path: "/v1/forecast"}}, + } + s.JSONEq(`[{"kind":"http"}]`, s.sourcesJSON(rule)) +} diff --git a/acceleration/internal/api/connectors_test.go b/acceleration/internal/api/connectors_test.go index 9133cde2b2..c3bdc19432 100644 --- a/acceleration/internal/api/connectors_test.go +++ b/acceleration/internal/api/connectors_test.go @@ -185,10 +185,12 @@ func (s *ConnectorsSuite) TestWhatTheRouterReadsToConnectIsNeverShown() { s.Require().NoError(json.Unmarshal(raw, &shown)) for _, withheld := range []string{ "endpoints", "vars", "authorize_params", "token_params", "identity", "capture", - "refresh", "rate_limit", "sources", "hooks", "manifest", + "refresh", "rate_limit", "hooks", "manifest", } { s.NotContains(shown, withheld) } + // The sources are shown by kind alone (TestAConnectorShowsItsSourceKindAndNoAddress). + s.Equal([]any{map[string]any{"kind": "mcp"}}, shown["sources"]) // The manifest's channel block stays withheld; AI-1053 shows only whether there is one. s.IsType(false, shown["channel"]) client, ok := shown["client"].(map[string]any) @@ -212,8 +214,8 @@ func (s *ConnectorsSuite) TestACustomConnectorsEndpointIsNeverShown() { // TestABuiltInReadsAsBeforeOnARouterWithoutAPublicURL is the control for AI-1046 and AI-1047: // the keys a built-in is answered with are the ones accelerate at 26051062 answered with, -// probed there with this suite (pr-w7/author-1.md), plus channel (AI-1053). Without ROUTER_PUBLIC_URL there is no -// redirect URI. +// probed there with this suite (pr-w7/author-1.md), plus channel (AI-1053) and sources +// (AI-3871). Without ROUTER_PUBLIC_URL there is no redirect URI. func (s *ConnectorsSuite) TestABuiltInReadsAsBeforeOnARouterWithoutAPublicURL() { for _, id := range []string{"slack", "linear", "telnyx"} { status, raw := s.serverClient.call(http.MethodGet, "/v1/agents/connectors/"+id, nil) @@ -221,7 +223,7 @@ func (s *ConnectorsSuite) TestABuiltInReadsAsBeforeOnARouterWithoutAPublicURL() var shown map[string]any s.Require().NoError(json.Unmarshal(raw, &shown)) s.Equal([]string{"category", "channel", "client", "created_at", "custom", "description", "duration", "id", "inputs", - "name", "revision", "schemes", "scopes"}, slices.Sorted(maps.Keys(shown)), id) + "name", "revision", "schemes", "scopes", "sources"}, slices.Sorted(maps.Keys(shown)), id) } } @@ -892,7 +894,8 @@ WHERE datname = current_database() AND wait_event_type = 'Lock' // TestAnMCPConnectorIsAnsweredAsBefore is the control for AI-3676: a custom MCP connector's // create, and the refusals of its endpoint, answer as on 5a798ad5d, probed there with this -// request (AI-3676/base-probe.txt): the same keys and values, and the same messages. +// request (AI-3676/base-probe.txt): the same keys and values, and the same messages. The one +// change is AI-3871's sources. func (s *ConnectorsSuite) TestAnMCPConnectorIsAnsweredAsBefore() { id := s.customID() status, raw := s.serverClient.call(http.MethodPost, "/v1/agents/connectors", s.customConnector(id)) @@ -900,13 +903,14 @@ func (s *ConnectorsSuite) TestAnMCPConnectorIsAnsweredAsBefore() { s.Require().Equal(http.StatusOK, status) var shown map[string]any s.Require().NoError(json.Unmarshal(raw, &shown)) - s.Equal([]string{"channel", "client", "created_at", "custom", "duration", "id", "inputs", "name", "revision", "schemes", "scopes"}, + s.Equal([]string{"channel", "client", "created_at", "custom", "duration", "id", "inputs", "name", "revision", "schemes", "scopes", "sources"}, slices.Sorted(maps.Keys(shown))) for _, key := range []string{"created_at", "duration"} { delete(shown, key) } s.Equal(map[string]any{"channel": false, "client": map[string]any{"registration": []any{"dcr"}}, "custom": true, "id": id, - "inputs": []any{}, "name": "Our CRM", "revision": float64(1), "schemes": []any{"oauth2_code"}, "scopes": []any{}}, shown) + "inputs": []any{}, "name": "Our CRM", "revision": float64(1), "schemes": []any{"oauth2_code"}, "scopes": []any{}, + "sources": []any{map[string]any{"kind": "mcp"}}}, shown) for endpoint, message := range map[string]string{ "https://10.0.0.7/mcp": "endpoint must be a public https URL without userinfo, query or fragment", @@ -950,7 +954,7 @@ func (s *ConnectorsSuite) TestACustomHTTPConnectorIsStoredAndItsAPIIsNeverShown( status, raw := s.serverClient.call(http.MethodGet, path, nil) s.Require().Equal(http.StatusOK, status) s.Contains(string(raw), id, path) - for _, hidden := range []string{"8.8.8.8", "base_url", `"http"`, "/v1/forecast", "get_forecast"} { + for _, hidden := range []string{"8.8.8.8", "base_url", `"http":`, "/v1/forecast", "get_forecast"} { s.NotContains(string(raw), hidden, path) } } @@ -1175,6 +1179,47 @@ func (s *ConnectorsSuite) httpConnector(id string) map[string]any { } } +// TestAConnectorShowsItsSourceKindAndNoAddress is AC of AI-3871: an http custom connector reads +// sources [{kind: http}] and an MCP one [{kind: mcp}], in the create's answer, the read and +// the list, and none of them shows a URL, a path or a tool. A built-in shows its kind too. +func (s *ConnectorsSuite) TestAConnectorShowsItsSourceKindAndNoAddress() { + httpID, mcpID := s.customID(), s.customID() + created := map[string]string{} + for id, sent := range map[string]map[string]any{httpID: s.httpConnector(httpID), mcpID: s.customConnector(mcpID)} { + status, raw := s.serverClient.call(http.MethodPost, "/v1/agents/connectors", sent) + s.Require().Equal(http.StatusOK, status, string(raw)) + created[id] = string(raw) + } + read := func(id string) string { + status, raw := s.serverClient.call(http.MethodGet, "/v1/agents/connectors/"+id, nil) + s.Require().Equal(http.StatusOK, status, string(raw)) + return string(raw) + } + sourcesOf := func(raw string) any { + var shown map[string]any + s.Require().NoError(json.Unmarshal([]byte(raw), &shown), raw) + return shown["sources"] + } + httpKind, mcpKind := []any{map[string]any{"kind": "http"}}, []any{map[string]any{"kind": "mcp"}} + + for id, want := range map[string][]any{httpID: httpKind, mcpID: mcpKind} { + s.Equal(want, sourcesOf(created[id]), "created "+id) + s.Equal(want, sourcesOf(read(id)), "read "+id) + for _, raw := range []string{created[id], read(id)} { + for _, address := range []string{"base_url", "endpoint", "8.8.8.8", "/v1/forecast", "get_forecast", "http_tools"} { + s.NotContains(raw, address, id) + } + } + } + listed := map[string][]ConnectorSource{} + for _, item := range s.list("").Items { + listed[item.ID] = item.Sources + } + s.Equal([]ConnectorSource{{Kind: "http"}}, listed[httpID]) + s.Equal([]ConnectorSource{{Kind: "mcp"}}, listed[mcpID]) + s.Equal([]ConnectorSource{{Kind: "mcp"}}, listed["slack"]) +} + // customConnector is a custom MCP connector the router accepts. Its endpoint is a public IP // literal, so checking it resolves nothing. func (s *ConnectorsSuite) customConnector(id string) map[string]any { diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py index ebaafbca39..a6c94280c5 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py @@ -213,6 +213,8 @@ from .connector_sandbox import ConnectorSandbox from .connector_setup import ConnectorSetup from .connector_setup_step import ConnectorSetupStep +from .connector_source import ConnectorSource +from .connector_source_kind import ConnectorSourceKind from .connector_tool_grant import ConnectorToolGrant from .contact import Contact from .contact_attempt import ContactAttempt @@ -891,6 +893,8 @@ "ConnectorSandbox", "ConnectorSetup", "ConnectorSetupStep", + "ConnectorSource", + "ConnectorSourceKind", "ConnectorToolGrant", "Contact", "ContactAttempt", diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/connector.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/connector.py index c63d714434..20f434703d 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/connector.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/connector.py @@ -15,6 +15,7 @@ from ..models.connector_input import ConnectorInput from ..models.connector_sandbox import ConnectorSandbox from ..models.connector_setup import ConnectorSetup + from ..models.connector_source import ConnectorSource T = TypeVar("T", bound="Connector") @@ -41,6 +42,9 @@ class Connector: it is reconnected. schemes (list[str] | None): How a connection may authenticate, such as oauth2_code. scopes (list[str] | None): The scopes a consent asks for. + sources (list[ConnectorSource]): How the connector's tools are reached, one entry per source, by kind only: + never a URL, a path or a credential. A custom connector made from an endpoint is mcp, one made from http is + http. category (str | Unset): description (str | Unset): redirect_uri (str | Unset): The redirect URI an OAuth client registered for this connector has to list: where @@ -64,6 +68,7 @@ class Connector: revision: int schemes: list[str] | None scopes: list[str] | None + sources: list[ConnectorSource] category: str | Unset = UNSET description: str | Unset = UNSET redirect_uri: str | Unset = UNSET @@ -111,6 +116,11 @@ def to_dict(self) -> dict[str, Any]: else: scopes = self.scopes + sources = [] + for sources_item_data in self.sources: + sources_item = sources_item_data.to_dict() + sources.append(sources_item) + category = self.category description = self.description @@ -141,6 +151,7 @@ def to_dict(self) -> dict[str, Any]: "revision": revision, "schemes": schemes, "scopes": scopes, + "sources": sources, } ) if category is not UNSET: @@ -164,6 +175,7 @@ def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: from ..models.connector_input import ConnectorInput from ..models.connector_sandbox import ConnectorSandbox from ..models.connector_setup import ConnectorSetup + from ..models.connector_source import ConnectorSource d = dict(src_dict) channel = d.pop("channel") @@ -232,6 +244,13 @@ def _parse_scopes(data: object) -> list[str] | None: scopes = _parse_scopes(d.pop("scopes")) + sources = [] + _sources = d.pop("sources") + for sources_item_data in _sources: + sources_item = ConnectorSource.from_dict(sources_item_data) + + sources.append(sources_item) + category = d.pop("category", UNSET) description = d.pop("description", UNSET) @@ -265,6 +284,7 @@ def _parse_scopes(data: object) -> list[str] | None: revision=revision, schemes=schemes, scopes=scopes, + sources=sources, category=category, description=description, redirect_uri=redirect_uri, diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source.py new file mode 100644 index 0000000000..b58fb808a6 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from typing_extensions import Self + +from ..models.connector_source_kind import ConnectorSourceKind + +T = TypeVar("T", bound="ConnectorSource") + + +@_attrs_define +class ConnectorSource: + """One way a connector's tools are reached. Only its kind is shown. + + Attributes: + kind (ConnectorSourceKind): mcp is an MCP server that lists the tools, http an HTTP API whose tools the manifest + lists. + """ + + kind: ConnectorSourceKind + + def to_dict(self) -> dict[str, Any]: + kind = self.kind.value + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "kind": kind, + } + ) + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + kind = ConnectorSourceKind._decode(d.pop("kind")) + + connector_source = cls( + kind=kind, + ) + + return connector_source diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source_kind.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source_kind.py new file mode 100644 index 0000000000..76f04fb503 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/connector_source_kind.py @@ -0,0 +1,29 @@ +from enum import StrEnum + + +class ConnectorSourceKind(StrEnum): + CONNECTOR_SOURCE_KIND_HTTP = "http" + CONNECTOR_SOURCE_KIND_MCP = "mcp" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def _decode(cls, value: object) -> "ConnectorSourceKind": + """Reads the value from an answer. A string this client does not list yet is kept as a member of its own, + so an answer from a newer router still reads, and is written back as it came.""" + try: + return cls(value) + except ValueError: + if not isinstance(value, str): + raise + member = str.__new__(cls, value) + member._name_ = value + member._value_ = value + return member + + def __reduce_ex__(self, protocol: object) -> object: + """Pickles a member this client does not list through _decode, as Enum's own reduce would call cls(value).""" + if self._value_ in type(self)._value2member_map_: + return super().__reduce_ex__(protocol) + return type(self)._decode, (self._value_,) diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs index 81cf5c8741..73d77a50ea 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -5312,6 +5312,12 @@ public partial class Connector [System.Text.Json.Serialization.JsonPropertyName("setup")] public ConnectorSetup? Setup { get; set; } = default!; + /// + /// How the connector's tools are reached, one entry per source, by kind only: never a URL, a path or a credential. A custom connector made from an endpoint is mcp, one made from http is http. + /// + [System.Text.Json.Serialization.JsonPropertyName("sources")] + public System.Collections.Generic.List Sources { get; set; } = new System.Collections.Generic.List(); + /// /// The fingerprint of the file the CLI last synced onto this connector. Absent on a built-in, and on a connector that was never synced or was written since by anything that is not a sync. /// @@ -6012,6 +6018,18 @@ public partial class ConnectorSetupStep } + /// + /// One way a connector's tools are reached. Only its kind is shown. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class ConnectorSource + { + + [System.Text.Json.Serialization.JsonPropertyName("kind")] + public string Kind { get; set; } = default!; + + } + /// /// One tool a binding allows. /// diff --git a/sdks/go/acceleration/enums_test.go b/sdks/go/acceleration/enums_test.go index 1375c5f195..058f5c464d 100644 --- a/sdks/go/acceleration/enums_test.go +++ b/sdks/go/acceleration/enums_test.go @@ -60,3 +60,17 @@ func TestCustomHTTPToolMethodNamesItsConstants(t *testing.T) { } } } + +// TestConnectorSourceKindNamesItsConstants pins prefixed names for the source kinds, so the next +// enum with mcp or http in it renames nothing callers already use. +func TestConnectorSourceKindNamesItsConstants(t *testing.T) { + named := map[acceleration.ConnectorSourceKind]string{ + acceleration.ConnectorSourceKindMCP: "mcp", + acceleration.ConnectorSourceKindHTTP: "http", + } + for constant, value := range named { + if string(constant) != value { + t.Errorf("%q is spelled %q", value, constant) + } + } +} diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 4f3cfa3b25..795cae7464 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -1018,6 +1018,24 @@ func (e ConnectorOnInterrupt) Valid() bool { } } +// Defines values for ConnectorSourceKind. +const ( + ConnectorSourceKindHTTP ConnectorSourceKind = "http" + ConnectorSourceKindMCP ConnectorSourceKind = "mcp" +) + +// Valid indicates whether the value is a known member of the ConnectorSourceKind enum. +func (e ConnectorSourceKind) Valid() bool { + switch e { + case ConnectorSourceKindHTTP: + return true + case ConnectorSourceKindMCP: + return true + default: + return false + } +} + // Defines values for ContactStage. const ( ContactStageCompleted ContactStage = "completed" @@ -5821,6 +5839,9 @@ type Connector struct { // Setup What a person does at the provider before the first consent. Setup *ConnectorSetup `json:"setup,omitempty"` + // Sources How the connector's tools are reached, one entry per source, by kind only: never a URL, a path or a credential. A custom connector made from an endpoint is mcp, one made from http is http. + Sources []ConnectorSource `json:"sources"` + // SyncHash The fingerprint of the file the CLI last synced onto this connector. Absent on a built-in, and on a connector that was never synced or was written since by anything that is not a sync. SyncHash *string `json:"sync_hash,omitempty"` } @@ -6115,6 +6136,15 @@ type ConnectorSetupStep struct { Title string `json:"title"` } +// ConnectorSource One way a connector's tools are reached. Only its kind is shown. +type ConnectorSource struct { + // Kind mcp is an MCP server that lists the tools, http an HTTP API whose tools the manifest lists. + Kind ConnectorSourceKind `json:"kind"` +} + +// ConnectorSourceKind mcp is an MCP server that lists the tools, http an HTTP API whose tools the manifest lists. +type ConnectorSourceKind string + // ConnectorToolGrant One tool a binding allows. type ConnectorToolGrant struct { // Name The tool as the connector names it. diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index b18f1f7784..9fc1f6530b 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -6581,6 +6581,8 @@ export type components = { readonly scopes: readonly string[] | null; /** @description What a person does at the provider before the first consent, such as registering an OAuth client. Absent when the manifest says nothing. */ readonly setup?: components["schemas"]["ConnectorSetup"]; + /** @description How the connector's tools are reached, one entry per source, by kind only: never a URL, a path or a credential. A custom connector made from an endpoint is mcp, one made from http is http. */ + readonly sources: readonly components["schemas"]["ConnectorSource"][]; /** @description The fingerprint of the file the CLI last synced onto this connector. Absent on a built-in, and on a connector that was never synced or was written since by anything that is not a sync. */ readonly sync_hash?: string; }; @@ -6842,6 +6844,15 @@ export type components = { readonly description: string; readonly title: string; }; + /** @description One way a connector's tools are reached. Only its kind is shown. */ + readonly ConnectorSource: { + readonly kind: components["schemas"]["ConnectorSourceKind"]; + }; + /** + * @description mcp is an MCP server that lists the tools, http an HTTP API whose tools the manifest lists. + * @enum {string} + */ + readonly ConnectorSourceKind: "mcp" | "http"; /** @description One tool a binding allows. */ readonly ConnectorToolGrant: { /** @description The tool as the connector names it. */ diff --git a/sdks/php/src/Generated/Connector.php b/sdks/php/src/Generated/Connector.php index 14181b2c90..51d5f724cd 100644 --- a/sdks/php/src/Generated/Connector.php +++ b/sdks/php/src/Generated/Connector.php @@ -37,6 +37,9 @@ public function __construct( // The scopes a consent asks for. /** @var list */ public array $scopes, + // How the connector's tools are reached, one entry per source, by kind only: never a URL, a path or a credent... + /** @var list */ + public array $sources, public ?string $category = null, public ?string $description = null, // The redirect URI an OAuth client registered for this connector has to list: where every consent of this dep... @@ -66,6 +69,7 @@ public static function fromArray(array $data): self revision: Json::int($data, 'revision'), schemes: Json::strings($data, 'schemes'), scopes: Json::strings($data, 'scopes'), + sources: array_map(ConnectorSource::fromArray(...), Json::objects($data, 'sources')), category: array_key_exists('category', $data) && $data['category'] !== null ? Json::string($data, 'category') : null, description: array_key_exists('description', $data) && $data['description'] !== null ? Json::string($data, 'description') : null, redirectUri: array_key_exists('redirect_uri', $data) && $data['redirect_uri'] !== null ? Json::string($data, 'redirect_uri') : null, @@ -93,6 +97,7 @@ public function toArray(): array $out['revision'] = $this->revision; $out['schemes'] = $this->schemes; $out['scopes'] = $this->scopes; + $out['sources'] = array_map(static fn (ConnectorSource $each): array => $each->toArray(), $this->sources); if ($this->category !== null) { $out['category'] = $this->category; } diff --git a/sdks/php/src/Generated/ConnectorSource.php b/sdks/php/src/Generated/ConnectorSource.php new file mode 100644 index 0000000000..9b0bceb30a --- /dev/null +++ b/sdks/php/src/Generated/ConnectorSource.php @@ -0,0 +1,42 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self( + kind: Json::enum($data, 'kind', ConnectorSourceKind::class), + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['kind'] = Json::enumValue($this->kind); + return $out; + } +} diff --git a/sdks/php/src/Generated/ConnectorSourceKind.php b/sdks/php/src/Generated/ConnectorSourceKind.php new file mode 100644 index 0000000000..ca499eb9b3 --- /dev/null +++ b/sdks/php/src/Generated/ConnectorSourceKind.php @@ -0,0 +1,16 @@ + { - properties: %w[category channel client created_at custom description id inputs name redirect_uri revision sandbox schemes scopes setup sync_hash].freeze, - required: %w[id revision name custom schemes inputs scopes client channel created_at].freeze, open: false + properties: %w[category channel client created_at custom description id inputs name redirect_uri revision sandbox schemes scopes setup sources sync_hash].freeze, + required: %w[id revision name custom schemes inputs scopes sources client channel created_at].freeze, open: false }.freeze, "ConnectorAuditCredential" => { properties: %w[access_expires_at access_fingerprint previous_access_fingerprint previous_refresh_fingerprint refresh_expires_at refresh_fingerprint rotated].freeze, @@ -2367,6 +2367,10 @@ module Generated properties: %w[description title].freeze, required: %w[title description].freeze, open: false }.freeze, + "ConnectorSource" => { + properties: %w[kind].freeze, + required: %w[kind].freeze, open: false + }.freeze, "ConnectorToolGrant" => { properties: %w[name schema_digest].freeze, required: %w[name].freeze, open: false diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs index c517dba38d..88dcb82ae2 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -4033,6 +4033,8 @@ pub struct Connector { ///What a person does at the provider before the first consent, such as registering an OAuth client. Absent when the manifest says nothing. #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub setup: ::std::option::Option, + ///How the connector's tools are reached, one entry per source, by kind only: never a URL, a path or a credential. A custom connector made from an endpoint is mcp, one made from http is http. + pub sources: ::std::vec::Vec, ///The fingerprint of the file the CLI last synced onto this connector. Absent on a built-in, and on a connector that was never synced or was written since by anything that is not a sync. #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub sync_hash: ::std::option::Option<::std::string::String>, @@ -4675,6 +4677,58 @@ pub struct ConnectorSetupStep { pub description: ::std::string::String, pub title: ::std::string::String, } +///One way a connector's tools are reached. Only its kind is shown. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct ConnectorSource { + pub kind: ConnectorSourceKind, +} +///mcp is an MCP server that lists the tools, http an HTTP API whose tools the manifest lists. +#[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, +)] +pub enum ConnectorSourceKind { + #[serde(rename = "mcp")] + Mcp, + #[serde(rename = "http")] + Http, + /// A value this SDK's spec does not list, as the router sent it. + #[serde(untagged)] + Unlisted(::std::string::String), +} +impl ::std::fmt::Display for ConnectorSourceKind { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Mcp => f.write_str("mcp"), + Self::Http => f.write_str("http"), + Self::Unlisted(ref value) => f.write_str(value), + } + } +} +impl ::std::str::FromStr for ConnectorSourceKind { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "mcp" => Ok(Self::Mcp), + "http" => Ok(Self::Http), + _ => Err("invalid value".into()), + } + } +} +impl ::std::convert::TryFrom<&str> for ConnectorSourceKind { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } +} +impl ::std::convert::TryFrom<::std::string::String> for ConnectorSourceKind { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } +} ///One tool a binding allows. #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] pub struct ConnectorToolGrant { From 73e80f230e4f42b50e27521088b293deb968fa75 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 19:04:02 +0100 Subject: [PATCH 06/13] [AI-3870] Pin delegation's pinned-digest check; own SDK note for AI-3871 (#2480) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Targets `feature/ai-3669-http-connectors`, not main. Two small leftovers of AI-3669; tests and docs only, no router code changes. ``` acceleration/internal/api/child_agents_sensitive_test.go +TestADelegationJudgesAnHTTPToolReadOnlyOnlyAtTheDigestItsGrantPins .claude/skills/sdk/notes/2026-11-24-ai-3676.md Connector sentence true again .claude/skills/sdk/notes/2026-11-25-ai-3871.md new: the AI-3871 `sources` note, moved here ``` ## 1. Delegation judges an http tool by its pinned digest `bindingSendsOut` (`sensitive.go`) calls `GrantSendsOut`, which judges an http tool at the digest its grant pins. Replacing that call with `manifest.SendsOutTool(tool.Name)` passed every ChildAgentsSuite test. The new test wires, past the API, a parent and a child with nessy (sensitive) and an http connector whose latest revision has `get`, a read-only GET: | grant | sensitive parent, http child | sensitive child, http parent | |---|---|---| | pins the digest | runs | runs | | pins none | refused | refused | | pins another digest | refused | refused | Mutants (one script, `mutate.sh`): `bindingSendsOut` -> `SendsOutTool`, `digest != grant.SchemaDigest` -> `digest == ""` and `-> digest == grant.SchemaDigest` each fail the test; the head passes. ## 2. SDK notes #2464 appended the AI-3871 part to the AI-3676 note; `notes/README.md` asks one file per change, and the AI-3676 note said the `Connector` is unchanged. The AI-3871 paragraph is now `2026-11-25-ai-3871.md` unchanged; the AI-3676 note is back as #2344 wrote it, except that its `Connector` sentence says "unchanged by this change" and points to the new note. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Sonnet 5.5 --- .../skills/sdk/notes/2026-11-24-ai-3676.md | 4 +- .../skills/sdk/notes/2026-11-25-ai-3871.md | 1 + .../api/child_agents_sensitive_test.go | 61 +++++++++++++++++++ 3 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 .claude/skills/sdk/notes/2026-11-25-ai-3871.md diff --git a/.claude/skills/sdk/notes/2026-11-24-ai-3676.md b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md index a3f9cf816f..84f6c9038d 100644 --- a/.claude/skills/sdk/notes/2026-11-24-ai-3676.md +++ b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md @@ -1,3 +1 @@ -`createConnector` (`POST /v1/agents/connectors`) takes an HTTP API in place of an MCP server (AI-3676). `CustomConnectorRequest` has a new optional `http`, a `CustomHTTPAPI` `{base_url, tools}`. Each tool is a `CustomHTTPTool` `{name, description, method, path, parameters, read_only}`: `method` is one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH` and `DELETE`, and `parameters` maps a name to a `CustomHTTPParameter` `{type, description, required}`, whose `type` is one of `string`, `number`, `integer` and `boolean`. `endpoint` is no longer required: a request sends a non-empty `endpoint` or `http`, not both. This breaks existing callers in four SDKs. In Go, `CustomConnectorRequest.Endpoint` is now a `*string` (`sdks/go/acceleration/generated.go`), and a caller that set it as a string now sets a pointer. In Rust, `CustomConnectorRequest.endpoint` is now an `Option` (`sdks/rust/src/types.rs`), so a struct literal or a read of a `String` no longer compiles. In PHP (`sdks/php/src/Generated/CustomConnectorRequest.php`) and Python (`plugins/stream`, `_generated/models/custom_connector_request.py`), `endpoint` moves from the first constructor argument to after `schemes`, so a positional call no longer matches; named and keyword arguments still work. The `Connector` the router answers is unchanged, so it shows neither `base_url` nor the tools. Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients. Other SDKs need to update: a `connectors.create` resource method, where an SDK has one, takes `http` beside `endpoint`. Swift, Kotlin and Dart need nothing, since `createConnector` is not client-accessible. - -The `Connector` the router answers now has `sources` (AI-3871), a list of `ConnectorSource` `{kind}` whose `kind` is `mcp` or `http`: a custom connector made from an `endpoint` reads `mcp`, one made from `http` reads `http`, and a built-in names its own. It never carries a URL, a path or a tool. This adds a required field to a response, so a client that builds a `Connector` itself, or compares one whole, must give it `sources`. In Go it is `[]ConnectorSource`, and the constants are `ConnectorSourceKindMCP` and `ConnectorSourceKindHTTP`. Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients; Swift, Kotlin and Dart generate nothing new. Other SDKs need to update: a resource method that returns a connector (`connectors.get`, `connectors.list`), where an SDK has one, exposes `sources`, so a caller can tell an http connector from an MCP one. +`createConnector` (`POST /v1/agents/connectors`) takes an HTTP API in place of an MCP server (AI-3676). `CustomConnectorRequest` has a new optional `http`, a `CustomHTTPAPI` `{base_url, tools}`. Each tool is a `CustomHTTPTool` `{name, description, method, path, parameters, read_only}`: `method` is one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH` and `DELETE`, and `parameters` maps a name to a `CustomHTTPParameter` `{type, description, required}`, whose `type` is one of `string`, `number`, `integer` and `boolean`. `endpoint` is no longer required: a request sends a non-empty `endpoint` or `http`, not both. This breaks existing callers in four SDKs. In Go, `CustomConnectorRequest.Endpoint` is now a `*string` (`sdks/go/acceleration/generated.go`), and a caller that set it as a string now sets a pointer. In Rust, `CustomConnectorRequest.endpoint` is now an `Option` (`sdks/rust/src/types.rs`), so a struct literal or a read of a `String` no longer compiles. In PHP (`sdks/php/src/Generated/CustomConnectorRequest.php`) and Python (`plugins/stream`, `_generated/models/custom_connector_request.py`), `endpoint` moves from the first constructor argument to after `schemes`, so a positional call no longer matches; named and keyword arguments still work. The `Connector` the router answers is unchanged by this change, so it shows neither `base_url` nor the tools; AI-3871 gives it `sources` (`2026-11-25-ai-3871.md`). Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients. Other SDKs need to update: a `connectors.create` resource method, where an SDK has one, takes `http` beside `endpoint`. Swift, Kotlin and Dart need nothing, since `createConnector` is not client-accessible. diff --git a/.claude/skills/sdk/notes/2026-11-25-ai-3871.md b/.claude/skills/sdk/notes/2026-11-25-ai-3871.md new file mode 100644 index 0000000000..45cf7918f9 --- /dev/null +++ b/.claude/skills/sdk/notes/2026-11-25-ai-3871.md @@ -0,0 +1 @@ +The `Connector` the router answers now has `sources` (AI-3871), a list of `ConnectorSource` `{kind}` whose `kind` is `mcp` or `http`: a custom connector made from an `endpoint` reads `mcp`, one made from `http` reads `http`, and a built-in names its own. It never carries a URL, a path or a tool. This adds a required field to a response, so a client that builds a `Connector` itself, or compares one whole, must give it `sources`. In Go it is `[]ConnectorSource`, and the constants are `ConnectorSourceKindMCP` and `ConnectorSourceKindHTTP`. Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients; Swift, Kotlin and Dart generate nothing new. Other SDKs need to update: a resource method that returns a connector (`connectors.get`, `connectors.list`), where an SDK has one, exposes `sources`, so a caller can tell an http connector from an MCP one. diff --git a/acceleration/internal/api/child_agents_sensitive_test.go b/acceleration/internal/api/child_agents_sensitive_test.go index 2fb0d10482..6d44f37c90 100644 --- a/acceleration/internal/api/child_agents_sensitive_test.go +++ b/acceleration/internal/api/child_agents_sensitive_test.go @@ -4,10 +4,13 @@ package api import ( "encoding/json" + "maps" "net/http" "strconv" "strings" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/harness" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) @@ -126,6 +129,44 @@ func (s *ChildAgentsSuite) TestADelegationRunsBesideASensitiveChildTheParentDoes s.Contains(run.FinalText, "tool: be brief") } +// An http tool that only reads at the latest revision reads only for a grant that pins that +// revision's digest: a session opens it at the digest its grant pins, or pins one on first use. +// Beside a sensitive connector, in the parent or in a child, a delegation so runs for the pinned +// grant and is refused for a grant that pins no digest or another one (AI-3675). +func (s *ChildAgentsSuite) TestADelegationJudgesAnHTTPToolReadOnlyOnlyAtTheDigestItsGrantPins() { + s.useInternalApp() + id, digest := s.readOnlyHTTPConnector() + for name, c := range map[string]struct { + grant store.ToolGrant + refused bool + }{ + "pinned": {store.ToolGrant{Name: "get", SchemaDigest: digest}, false}, + "pinned nothing": {store.ToolGrant{Name: "get"}, true}, + "pinned another": {store.ToolGrant{Name: "get", SchemaDigest: strings.Repeat("0", len(digest))}, true}, + } { + api := store.ConnectorBinding{Name: "api", ConnectorID: id, Connection: store.ConnectionBinding{Type: "session"}, + Tools: []store.ToolGrant{c.grant}} + nessy := store.ConnectorBinding{Name: "customers", ConnectorID: "nessy", Connection: store.ConnectionBinding{Type: "session"}, + Tools: []store.ToolGrant{{Name: "org_lookup"}}} + for layout, bindings := range map[string][2]store.ConnectorBinding{"sensitive parent": {nessy, api}, "sensitive child": {api, nessy}} { + parent := s.agentWith("fanning/fanning-model", nil) + child := s.agentWith("echo/echo-model", nil) + s.delegate(parent, map[string]AgentConfig{"ask_a": child}) + s.change(parent.Id, func(config *store.AgentConfig) { config.Connectors = []store.ConnectorBinding{bindings[0]} }) + s.change(child.Id, func(config *store.AgentConfig) { config.Connectors = []store.ConnectorBinding{bindings[1]} }) + + run := s.run(CreateRunRequest{ConfigId: parent.Id, Input: "review this"}) + + if c.refused { + s.refusedAll(run) + } else { + s.NotContains(run.FinalText, "was not run", name+", "+layout) + s.Contains(run.FinalText, "tool: be brief", name+", "+layout) + } + } + } +} + // TestADelegationWithNoSensitiveConnectorRuns is the control: on the base, dca845c2e, the // same graph answered the same (author-1.md, «Control probe»). func (s *ChildAgentsSuite) TestADelegationWithNoSensitiveConnectorRuns() { @@ -195,3 +236,23 @@ func (s *ChildAgentsSuite) refusedAll(run Run) { s.NotContains(run.FinalText, name, "the tool error names nothing of a server-side config") } } + +// readOnlyHTTPConnector is a custom connector whose latest revision has one http tool, get, a +// read-only GET, and the digest a grant pins to open it as listed there. Its manifest is +// linear.yaml's with an http source in place of its mcp one (as in ConfigsSuite). +func (s *ChildAgentsSuite) readOnlyHTTPConnector() (string, string) { + ctx := s.T().Context() + linear, err := s.store.ConnectorDefinitions.Latest(ctx, s.customerID(), "linear") + s.Require().NoError(err) + tool := core.HTTPTool{Name: "get", Description: "Reads the API.", Method: http.MethodGet, Path: "/get", ReadOnly: true} + manifest := linear.Manifest + manifest.ID = "custom_t" + strings.ReplaceAll(s.utils.uuid(), "-", "") + manifest.Endpoints = maps.Clone(manifest.Endpoints) + manifest.Endpoints[core.SourceKindHTTP] = "https://8.8.8.8/api" + manifest.Sources = []core.SourceRule{{Kind: core.SourceKindHTTP, Endpoint: core.SourceKindHTTP, HTTPTools: []core.HTTPTool{tool}}} + _, err = s.store.ConnectorDefinitions.Revise(ctx, s.customerID(), manifest) + s.Require().NoError(err) + digest, err := httpsource.ToolSchemaDigest(tool) + s.Require().NoError(err) + return manifest.ID, digest +} From 5ebafd47b4ce53d275fee2d6311f9366decfba73 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 13:12:58 -0500 Subject: [PATCH 07/13] AI-3669: the feature after main's custom connector limits (#2430) - An http tool's description and path caps are core's CustomDescriptionMaxLength and CustomEndpointMaxLength, which #2430 made the one home of those values, rather than 1000 and 2048 written again. - The feature's import tests name their definitions custom_a + a hex id: #2430 holds an imported id to the API's pattern, a letter after custom_, which a hex id need not start with. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/datamove_test.go | 2 +- acceleration/internal/connectors/core/http_tools.go | 10 ++++------ acceleration/internal/store/datamove_test.go | 6 +++--- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index 7290b5b991..ad2868c039 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -242,7 +242,7 @@ func (s *DataMoveSuite) TestAnImportedConnectorNamingTheOperatorsClientAfterAnot // connector the API would create (AI-3676), and refuses one whose API is on a private address // with the create's own message, storing nothing. func (s *DataMoveSuite) TestAnImportedHTTPConnectorIsCheckedAsTheAPIChecksIt() { - refused, taken := "custom_"+store.NewID(), "custom_"+store.NewID() + refused, taken := "custom_a"+store.NewID(), "custom_a"+store.NewID() line := func(id, base string) dataLine { return dataLine{Table: "connector_definitions", Row: json.RawMessage(`{"id": "` + id + `", "revision": 1, "name": "Acme", "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": {"id": "` + id + `", "revision": 1, diff --git a/acceleration/internal/connectors/core/http_tools.go b/acceleration/internal/connectors/core/http_tools.go index 87e7fb3a2d..36a0c92e7f 100644 --- a/acceleration/internal/connectors/core/http_tools.go +++ b/acceleration/internal/connectors/core/http_tools.go @@ -57,13 +57,11 @@ const ( // OpenAI documents taking in one request. maxHTTPTools = 128 // maxHTTPToolDescription is the cap a custom connector's own description has - // (CustomConnectorRequest.Description, internal/api/connectors.go), on a tool's description - // and on each of its parameters'. - maxHTTPToolDescription = 1000 + // (CustomDescriptionMaxLength), on a tool's description and on each of its parameters'. + maxHTTPToolDescription = CustomDescriptionMaxLength // maxHTTPPath is the cap a custom connector's MCP endpoint URL has - // (CustomConnectorRequest.Endpoint, internal/api/connectors.go), on a tool's path and on the - // http source's endpoint, its base URL. - maxHTTPPath = 2048 + // (CustomEndpointMaxLength), on a tool's path and on the http source's endpoint, its base URL. + maxHTTPPath = CustomEndpointMaxLength // maxHTTPParameters is the cap an agent config has on its connector bindings and its // visible_tools (internal/api/configs.go). maxHTTPParameters = 64 diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 0bcac2963c..7630442547 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -3082,7 +3082,7 @@ func (s *DataMoveSuite) TestAnImportedHTTPDefinitionWhoseAPIIsPrivateIsRefused() // its transaction opens, not row by row inside it. The first change names no table and fails // only once inside the transaction; the definition after it is refused first. func (s *DataMoveSuite) TestAChangesDefinitionsAreCheckedBeforeItsTransactionOpens() { - id := "custom_" + newID() + id := "custom_a" + newID() private := strings.Replace(strings.Replace(customWeather, "https://8.8.8.8/v1", "https://169.254.169.254/v1", 1), `"id": "custom_acme"`, `"id": "`+id+`"`, 1) @@ -3102,7 +3102,7 @@ func (s *DataMoveSuite) TestAChangesDefinitionsAreCheckedBeforeItsTransactionOpe // stored as the API would store it, as an import's is: the check before the transaction hands // its normalized row on (applyChanges). func (s *DataMoveSuite) TestAChangesDefinitionArrivesWithoutAFieldThisReleaseDoesNotRead() { - id := "custom_" + newID() + id := "custom_a" + newID() manifest := strings.Replace(customManifestWith(`"later": {"env": "GOOGLE"}`), "custom_acme", id, 1) err := s.destination.ApplyChanges(s.ctx, "moved", []DataChange{{Table: "connector_definitions", Op: ChangeInsert, @@ -3150,7 +3150,7 @@ func (s *DataMoveSuite) TestAnImportedDefinitionWhoseIDIsNoStringIsRefused() { } func (s *DataMoveSuite) TestAChangeCarryingADefinitionTheAPIWouldRefuseIsRefused() { - id := "custom_" + newID() + id := "custom_a" + newID() manifest := strings.Replace(customManifestWith(`"client": {"registration": ["operator"], "env": "GOOGLE"}, "schemes": ["oauth2_code"]`), "custom_acme", id, 1) From 74b3431a060fc448b759db77c2087eaeaea86a9d Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 13:13:42 -0500 Subject: [PATCH 08/13] AI-3669: each grant and layout of the http read-only delegation test runs as its own subtest (#2480 R1.1) A failure now names its case, the refused ones too. Co-Authored-By: Claude Opus 5.5 --- .../api/child_agents_sensitive_test.go | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/acceleration/internal/api/child_agents_sensitive_test.go b/acceleration/internal/api/child_agents_sensitive_test.go index 6d44f37c90..e4bea92aa8 100644 --- a/acceleration/internal/api/child_agents_sensitive_test.go +++ b/acceleration/internal/api/child_agents_sensitive_test.go @@ -149,20 +149,22 @@ func (s *ChildAgentsSuite) TestADelegationJudgesAnHTTPToolReadOnlyOnlyAtTheDiges nessy := store.ConnectorBinding{Name: "customers", ConnectorID: "nessy", Connection: store.ConnectionBinding{Type: "session"}, Tools: []store.ToolGrant{{Name: "org_lookup"}}} for layout, bindings := range map[string][2]store.ConnectorBinding{"sensitive parent": {nessy, api}, "sensitive child": {api, nessy}} { - parent := s.agentWith("fanning/fanning-model", nil) - child := s.agentWith("echo/echo-model", nil) - s.delegate(parent, map[string]AgentConfig{"ask_a": child}) - s.change(parent.Id, func(config *store.AgentConfig) { config.Connectors = []store.ConnectorBinding{bindings[0]} }) - s.change(child.Id, func(config *store.AgentConfig) { config.Connectors = []store.ConnectorBinding{bindings[1]} }) - - run := s.run(CreateRunRequest{ConfigId: parent.Id, Input: "review this"}) - - if c.refused { - s.refusedAll(run) - } else { - s.NotContains(run.FinalText, "was not run", name+", "+layout) - s.Contains(run.FinalText, "tool: be brief", name+", "+layout) - } + s.Run(name+", "+layout, func() { + parent := s.agentWith("fanning/fanning-model", nil) + child := s.agentWith("echo/echo-model", nil) + s.delegate(parent, map[string]AgentConfig{"ask_a": child}) + s.change(parent.Id, func(config *store.AgentConfig) { config.Connectors = []store.ConnectorBinding{bindings[0]} }) + s.change(child.Id, func(config *store.AgentConfig) { config.Connectors = []store.ConnectorBinding{bindings[1]} }) + + run := s.run(CreateRunRequest{ConfigId: parent.Id, Input: "review this"}) + + if c.refused { + s.refusedAll(run) + } else { + s.NotContains(run.FinalText, "was not run") + s.Contains(run.FinalText, "tool: be brief") + } + }) } } } From 6b221728d4b383ae1d58ed23dc6f0b2798571a3a Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 13:43:31 -0500 Subject: [PATCH 09/13] test: an http custom connector meets the limits of an MCP one Co-Authored-By: Claude Sonnet 5.5 --- .../internal/connectors/core/custom_test.go | 27 +++++++++++++++++++ .../internal/store/datamove_unit_test.go | 3 ++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/connectors/core/custom_test.go b/acceleration/internal/connectors/core/custom_test.go index 310be9d0e9..77a17b7f5c 100644 --- a/acceleration/internal/connectors/core/custom_test.go +++ b/acceleration/internal/connectors/core/custom_test.go @@ -280,6 +280,33 @@ func (s *CustomConnectorSuite) TestAScopeListedTwiceIsRefused() { s.ErrorContains(s.manifest(func(c *CustomConnector) { c.Scopes = []string{"read", "write", "read"} }), `scopes[2] "read" is listed twice`) } +// An http connector meets the same limits as an MCP one: CustomManifest checks them before it tells the two apart. +func (s *CustomConnectorSuite) TestAnHTTPConnectorMeetsTheLimitsOfAnMCPOne() { + for name, test := range map[string]struct { + edit func(*CustomConnector) + err string + }{ + "an id": {func(c *CustomConnector) { c.ID = "custom_9weather" }, "is not custom_ then a lowercase letter"}, + "a name": {func(c *CustomConnector) { c.Name = strings.Repeat("é", 121) }, "name is longer than 120 characters"}, + "a category": {func(c *CustomConnector) { c.Category = strings.Repeat("é", 81) }, "category is longer than 80 characters"}, + "a description": {func(c *CustomConnector) { c.Description = strings.Repeat("é", 1001) }, "description is longer than 1000 characters"}, + "a scope with a space": {func(c *CustomConnector) { c.Scopes = []string{"a b"} }, "scopes[0] is not an RFC 6749 scope token"}, + "a scope listed twice": {func(c *CustomConnector) { c.Scopes = []string{"a", "a"} }, "is listed twice"}, + } { + connector := httpCustom() + test.edit(&connector) + + _, err := CustomManifest(connector) + + s.ErrorContains(err, test.err, name) + } + + connector := httpCustom() + connector.Name, connector.Description = strings.Repeat("é", 120), strings.Repeat("é", 1000) + _, err := CustomManifest(connector) + s.NoError(err, "at the limits") +} + // An imported manifest reaches the limits through AsCustom. func (s *CustomConnectorSuite) TestAManifestPastALimitIsNoCustomOne() { manifest, err := CustomManifest(CustomConnector{ID: "custom_acme", Name: "Acme", Endpoint: "https://mcp.acme.example/mcp", Schemes: []string{"bearer"}}) diff --git a/acceleration/internal/store/datamove_unit_test.go b/acceleration/internal/store/datamove_unit_test.go index be625c771d..0022c884b0 100644 --- a/acceleration/internal/store/datamove_unit_test.go +++ b/acceleration/internal/store/datamove_unit_test.go @@ -68,7 +68,8 @@ func (s *ImportableDefinitionSuite) TestAnOversizedHTTPConnectorIsRefused() { for name, manifest := range map[string]string{ "a 2 MiB parameter description": strings.Replace(importedHTTP, `"parameters": {"id": {"type": "string", "required": true}}`, `"parameters": {"id": {"type": "string", "required": true}, "q": {"type": "string", "description": "`+strings.Repeat("x", 2<<20)+`"}}`, 1), - "a 4 KiB base_url": strings.Replace(importedHTTP, "https://8.8.8.8/api", "https://8.8.8.8/"+strings.Repeat("a", 4096), 1), + "a 121-character name": strings.Replace(importedHTTP, `"name": "CRM"`, `"name": "`+strings.Repeat("é", 121)+`"`, 1), + "a 4 KiB base_url": strings.Replace(importedHTTP, "https://8.8.8.8/api", "https://8.8.8.8/"+strings.Repeat("a", 4096), 1), } { _, err := importableDefinition(context.Background(), json.RawMessage(`{"id": "custom_crm", "manifest": `+manifest+`}`)) From 469960b4183df87a4a834f44636b3c19194b2ec7 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 20:20:48 +0100 Subject: [PATCH 10/13] [AI-3870] Fix the fake provider's CodeQL alert; SDK skill names http connectors (#2483) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Targets the feature branch `feature/ai-3669-http-connectors` (not main). Two Nits (R1.2, R1.3) from the joint review of #2312. ``` fakeprovider/api.go /rest/echo-credential 403 or 200 body: Content-Type application/json (was none: CodeQL alert 175) .claude/skills/sdk/SKILL.md:485 createConnector: "a custom connector, an MCP endpoint or an http API" -> notes/2026-11-24-ai-3676.md ``` - The fake is test code: `go list -deps ./cmd/router` has no fakeprovider. Behaviour is otherwise the same; no other handler in the package echoes request input (channel.go:170 is a static body). - Test: `TestFakeProviderSuite` now asserts `Content-Type: application/json` on both echo answers. Mutation: removing the `Set` line fails it. - Ran: `go test ./internal/connectors/fakeprovider/ ./internal/connectors/sources/http/`; `go test -tags integration -run TestSessionConnectorsSuite ./internal/api/` (the users of the fake API); both vets. CodeQL not run locally (no CLI): the PR's CodeQL check will tell. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Sonnet 5.5 --- .claude/skills/sdk/SKILL.md | 2 +- acceleration/internal/connectors/fakeprovider/api.go | 4 +++- .../internal/connectors/fakeprovider/fakeprovider_test.go | 4 ++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 346d4368df..d4c468ff69 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -482,7 +482,7 @@ SDK with a router has moved: `client.Router` (Go, .NET), `client.router` (Python Python, where `Router(...)` stays for the `url`/`customer_id` case. JavaScript has no router yet; when it gets one, start from `client.router(name)`. -Connector definitions can be listed, read and added. `listConnectors` (`GET /v1/agents/connectors`, with `q`, `limit` and `cursor`, answering a `ConnectorPage`), `getConnector` (`GET /v1/agents/connectors/{id}`) and `createConnector` (`POST /v1/agents/connectors`, a `CustomConnectorRequest` for a custom MCP server whose id starts with `custom_`) are all server-side only. A `Connector` shows the schemes, inputs, scopes and `client.registration` (where the OAuth client may come from, a list of `ConnectorClientRegistrationMethod`), never endpoints or the operator's client variables. Name them `connectors.list/get/create`, spelled the way the language spells them, with `list` following the cursor like `Items.Unwind`. Go has the regenerated client (`ListConnectors`, `GetConnector`, `CreateConnector`) and no resource methods yet. JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP need their generated clients regenerated and the three methods added. Swift, Kotlin and Dart need nothing, since none of the three is client-accessible. The schemas were named `ConnectorDefinition` and `ConnectorDefinitionPage` until October 5; they are `Connector` and `ConnectorPage` now, while the store keeps `ConnectorDefinition` for one stored revision. JavaScript and Python have the renamed generated types; .NET, Ruby, Rust and PHP pick the rename up when they regenerate. +Connector definitions can be listed, read and added. `listConnectors` (`GET /v1/agents/connectors`, with `q`, `limit` and `cursor`, answering a `ConnectorPage`), `getConnector` (`GET /v1/agents/connectors/{id}`) and `createConnector` (`POST /v1/agents/connectors`, a `CustomConnectorRequest` for a custom connector, an MCP endpoint or an http API (`.claude/skills/sdk/notes/2026-11-24-ai-3676.md`), whose id starts with `custom_`) are all server-side only. A `Connector` shows the schemes, inputs, scopes and `client.registration` (where the OAuth client may come from, a list of `ConnectorClientRegistrationMethod`), never endpoints or the operator's client variables. Name them `connectors.list/get/create`, spelled the way the language spells them, with `list` following the cursor like `Items.Unwind`. Go has the regenerated client (`ListConnectors`, `GetConnector`, `CreateConnector`) and no resource methods yet. JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP need their generated clients regenerated and the three methods added. Swift, Kotlin and Dart need nothing, since none of the three is client-accessible. The schemas were named `ConnectorDefinition` and `ConnectorDefinitionPage` until October 5; they are `Connector` and `ConnectorPage` now, while the store keeps `ConnectorDefinition` for one stored revision. JavaScript and Python have the renamed generated types; .NET, Ruby, Rust and PHP pick the rename up when they regenerate. Plugins, `plugin_events` and `mcp_servers` are removed (AI-1757): catalog plugins, their logins, options, events and logos, and MCP servers named by URL, were replaced by connectors (a built-in connector, or a custom one for a server's URL). The notes that described them are gone; what is left is the refusal: agent.yaml refuses the keys (AI-1784, AI-2531), the router answers a non-empty list with a 400 (AI-2538), and the generated clients no longer carry their types (AI-2772). diff --git a/acceleration/internal/connectors/fakeprovider/api.go b/acceleration/internal/connectors/fakeprovider/api.go index 872ceffe42..3be426c405 100644 --- a/acceleration/internal/connectors/fakeprovider/api.go +++ b/acceleration/internal/connectors/fakeprovider/api.go @@ -43,7 +43,8 @@ func (s *Server) APIRequests() []APIRequest { // /rest/echo-credential 403 whose body says the APIKeyHeader and Authorization it got, as an // API that echoes the request's credential in its error does; with // ?status=200, the same body as a 200, as one that echoes it in an -// answer does +// answer does; both are application/json, so a browser never reads the +// echoed request as HTML // anything else 200 "ok" func (s *Server) api(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) @@ -71,6 +72,7 @@ func (s *Server) api(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("status") == "200" { status = http.StatusOK } + w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _, _ = io.WriteString(w, `{"error":"key `+r.Header.Get(APIKeyHeader)+` and `+r.Header.Get("Authorization")+` may not read this"}`) return diff --git a/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go b/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go index 5e5caf1f47..54adf5bdb0 100644 --- a/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go +++ b/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go @@ -1175,6 +1175,7 @@ func (s *FakeProviderSuite) slack(srv *fakeprovider.Server, method, token string // and echoes the credential in /echo-credential's 403, or in its 200 with ?status=200. func (s *FakeProviderSuite) TestTheHTTPAPITakesItsKeyRecordsEachRequestAndAnswersByPath() { srv := fakeprovider.New(s.T()) + var contentType string send := func(method, path, key string) (int, string) { request, err := http.NewRequest(method, srv.URL+fakeprovider.PathAPI+path, strings.NewReader("sent")) s.Require().NoError(err) @@ -1184,6 +1185,7 @@ func (s *FakeProviderSuite) TestTheHTTPAPITakesItsKeyRecordsEachRequestAndAnswer defer response.Body.Close() body, err := io.ReadAll(response.Body) s.Require().NoError(err) + contentType = response.Header.Get("Content-Type") return response.StatusCode, string(body) } @@ -1205,9 +1207,11 @@ func (s *FakeProviderSuite) TestTheHTTPAPITakesItsKeyRecordsEachRequestAndAnswer status, body = send(http.MethodPost, "/echo-credential", srv.APIKey) s.Equal(http.StatusForbidden, status) s.Contains(body, srv.APIKey) + s.Equal("application/json", contentType, "the echoed request is not sniffed as HTML") status, body = send(http.MethodGet, "/echo-credential?status=200", srv.APIKey) s.Equal(http.StatusOK, status) s.Contains(body, srv.APIKey) + s.Equal("application/json", contentType) requests := srv.APIRequests() s.Require().Len(requests, 10, "the refused ones too") From 134c5939c478aa0c19566ef4d5fbb5014a0fd17d Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 20:43:13 -0500 Subject: [PATCH 11/13] chore: regenerate clients after merging main Co-Authored-By: Claude Opus 5.5 --- .../getstream/vision_agents/generated/spec.rb | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb index 9c7937396b..bd6517d2fc 100644 --- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb +++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb @@ -2304,8 +2304,8 @@ module Generated required: [].freeze, open: false }.freeze, "Connector" => { - properties: %w[category channel client created_at custom description id inputs name redirect_uri revision sandbox schemes scopes setup sync_hash].freeze, - required: %w[id revision name custom schemes inputs scopes client channel created_at].freeze, open: false + properties: %w[category channel client created_at custom description id inputs name redirect_uri revision sandbox schemes scopes setup sources sync_hash].freeze, + required: %w[id revision name custom schemes inputs scopes sources client channel created_at].freeze, open: false }.freeze, "ConnectorAuditCredential" => { properties: %w[access_expires_at access_fingerprint previous_access_fingerprint previous_refresh_fingerprint refresh_expires_at refresh_fingerprint rotated].freeze, @@ -2383,6 +2383,10 @@ module Generated properties: %w[description title].freeze, required: %w[title description].freeze, open: false }.freeze, + "ConnectorSource" => { + properties: %w[kind].freeze, + required: %w[kind].freeze, open: false + }.freeze, "ConnectorToolGrant" => { properties: %w[name schema_digest].freeze, required: %w[name].freeze, open: false @@ -2448,8 +2452,20 @@ module Generated required: %w[items has_more].freeze, open: false }.freeze, "CustomConnectorRequest" => { - properties: %w[category check_changes client description endpoint id name schemes scopes sync_hash].freeze, - required: %w[id name endpoint schemes].freeze, open: false + properties: %w[category check_changes client description endpoint http id name schemes scopes sync_hash].freeze, + required: %w[id name schemes].freeze, open: false + }.freeze, + "CustomHTTPAPI" => { + properties: %w[base_url tools].freeze, + required: %w[base_url tools].freeze, open: false + }.freeze, + "CustomHTTPParameter" => { + properties: %w[description required type].freeze, + required: %w[type].freeze, open: false + }.freeze, + "CustomHTTPTool" => { + properties: %w[description method name parameters path read_only].freeze, + required: %w[name description method path].freeze, open: false }.freeze, "CustomModel" => { properties: %w[base_url context_window created_at has_api_key id input_modalities model name per_million_input_tokens per_million_output_tokens retention target trains_on_data updated_at].freeze, From 8e36d3426b4f14ee62f46c07c2dc39be3bfc325b Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 20:45:01 -0500 Subject: [PATCH 12/13] test(api): an imported http connector is weighed by the sensitive rule at its tools' digests #2485 holds imported agent configs and connector definitions to the sensitive-connector rule; this pins that an http connector's tools are judged there by sensitive.GrantSendsOut: a POST and a read-only GET granted by name send data out, a read-only GET at its digest does not. Co-Authored-By: Claude Opus 5.5 --- .../internal/api/datamove_sensitive_test.go | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/acceleration/internal/api/datamove_sensitive_test.go b/acceleration/internal/api/datamove_sensitive_test.go index cf2b256b1c..9c5a7c2ddd 100644 --- a/acceleration/internal/api/datamove_sensitive_test.go +++ b/acceleration/internal/api/datamove_sensitive_test.go @@ -8,6 +8,8 @@ import ( "net/http" "strings" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) @@ -276,6 +278,45 @@ func (s *DataMoveSuite) TestAnImportedConnectorAnAgentBindsWithApprovalBesideASe s.Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+connector, nil, nil)) } +// An imported http connector's tools are weighed as a config write weighs them +// (sensitive.GrantSendsOut): a POST sends data out, and so does a read-only GET granted by +// name, which pins no digest; a read-only GET granted at its digest only reads. +func (s *DataMoveSuite) TestAnImportedHTTPConnectorAnAgentBindsBesideASensitiveOneIsWeighedByItsTools() { + template := s.agentTemplate() + get := core.HTTPTool{Name: "get_item", Description: "Reads an item.", Method: http.MethodGet, Path: "/items", ReadOnly: true} + digest, err := httpsource.ToolSchemaDigest(get) + s.Require().NoError(err) + for name, grant := range map[string]map[string]any{ + "a POST": {"name": "create_item"}, + "a read-only GET by name": {"name": "get_item"}, + "a read-only GET at its digest": {"name": "get_item", "schema_digest": digest}, + } { + s.useInternalApp() + connector := "custom_a" + store.NewID() + agent, _ := s.importedAgent(template, map[string]any{"connectors": []map[string]any{sessionNessy("customers"), + {"name": "api", "connector_id": connector, "connection": map[string]any{"type": "session"}, "tools": []map[string]any{grant}}}}) + definition := dataLine{Table: "connector_definitions", Row: json.RawMessage(`{"id": "` + connector + `", "revision": 1, + "name": "Acme", "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": {"id": "` + connector + `", + "revision": 1, "name": "Acme", "schemes": ["api_key"], "endpoints": {"http": "https://8.8.8.8"}, "sources": [{"kind": "http", + "endpoint": "http", "http_tools": [ + {"name": "get_item", "description": "Reads an item.", "method": "GET", "path": "/items", "read_only": true}, + {"name": "create_item", "description": "Creates an item.", "method": "POST", "path": "/items"}]}]}}`)} + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import", ndjson([]dataLine{agent, definition})) + + if name == "a read-only GET at its digest" { + s.Equal(http.StatusOK, status, failure) + s.Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+connector, nil, nil), name) + continue + } + s.Equal(http.StatusBadRequest, status, name) + s.Contains(failure, `store: import connector_definitions:{"id":"`+connector+`","revision":1}: the agent "`, name) + s.Contains(failure, `" binds it: connector binding "customers" binds "nessy", whose tools read private data, `+ + `and connector binding "api" can send data out`, name) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+connector, nil, nil), name) + } +} + // A definition is weighed with the agents of a config binding it too: a child binding it, whose // parent binds nessy. func (s *DataMoveSuite) TestAnImportedConnectorAChildBindsUnderASensitiveParentIsRefused() { From 0caa225c1fe2fbc310fa0f1743c5e791fee106e4 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 21:21:01 -0500 Subject: [PATCH 13/13] [AI-3831] Test a checked sync of an http connector over an edit no sync wrote Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/connectors_test.go | 21 ++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/acceleration/internal/api/connectors_test.go b/acceleration/internal/api/connectors_test.go index bf72239f4b..35454cbd40 100644 --- a/acceleration/internal/api/connectors_test.go +++ b/acceleration/internal/api/connectors_test.go @@ -1332,3 +1332,24 @@ func connectorIDs(definitions []Connector) []string { } return ids } + +// AI-3831 for an http connector: a checked sync is refused over a newest revision no sync wrote +// that says something else (here a tool's path), and goes through over one that says the same. +func (s *ConnectorsSuite) TestACheckedSyncOfAnHTTPConnectorIsRefusedOnlyOverAnEditNoSyncWrote() { + id := s.customID() + s.create(s.httpConnector(id)) + + synced := s.create(s.checked(s.httpConnector(id), "hash-one")) + s.Equal(1, synced.Revision, "what the newest revision already says is no change") + s.Equal("hash-one", s.get(id).SyncHash) + + edited := s.httpConnector(id) + edited["http"].(map[string]any)["tools"].([]map[string]any)[0]["path"] = "/v2/forecast" + s.create(edited) + stored := s.get(id) + s.Equal(2, stored.Revision) + + s.assertRefusedAsUnsynced(s.serverClient, http.MethodPost, "/v1/agents/connectors", + s.checked(s.httpConnector(id), "hash-two")) + s.Equal(stored, s.get(id), "a refused sync writes nothing") +}