diff --git a/.claude/skills/add-connector/SKILL.md b/.claude/skills/add-connector/SKILL.md index 5db4d9b100..9fd44352dc 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`, `sync_hash`, `check_changes`). - 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. - `sync_hash` is the fingerprint of the file the CLI synced the connector from. The connector returns it until a create without one, from the dashboard or the API, clears it. - `check_changes: true` refuses the create (409 `unsynced_changes`) when the newest revision has no diff --git a/.claude/skills/connectors/SKILL.md b/.claude/skills/connectors/SKILL.md index 9c68591e5b..572707226b 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` | @@ -184,8 +184,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 (`connectors/sensitive`, `ConfigComplaint`; across a parent and its child agents, `GraphComplaint`). 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/.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/.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..84f6c9038d --- /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 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/CHANGELOG.md b/CHANGELOG.md index aa2f9a2b63..72fccdee15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -710,6 +710,14 @@ 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 Rust SDK's `get_agent_log` takes a query `Client::get_agent_log(id)` is `get_agent_log(id, &GetAgentLogQuery { region })`: the router reads a log in the region it names, and `GetAgentLogQuery::default()` reads it in the region answering, as before. diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 0a5c35412d..104f1bab9a 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -3592,6 +3592,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 @@ -3604,6 +3609,7 @@ components: - schemes - inputs - scopes + - sources - client - channel - created_at @@ -4095,6 +4101,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: @@ -4699,7 +4723,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 @@ -4713,9 +4737,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}$ @@ -4751,9 +4778,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: @@ -16374,7 +16491,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 @@ -16412,7 +16529,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/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 3c2e144465..e78c5a8aaf 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" @@ -571,7 +572,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/api/child_agents_sensitive_test.go b/acceleration/internal/api/child_agents_sensitive_test.go index 5bbe87f3ac..63e9c53c70 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/sandbox" "github.com/GetStream/Vision-Agents/acceleration/internal/store" @@ -127,6 +130,46 @@ 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}} { + 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") + } + }) + } + } +} + // TestADelegationWithNoSensitiveConnectorRuns is the control: on the base, dca845c2e, the // same graph answered the same (author-1.md, «Control probe»). func (s *ChildAgentsSuite) TestADelegationWithNoSensitiveConnectorRuns() { @@ -244,3 +287,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 +} diff --git a/acceleration/internal/api/configs_test.go b/acceleration/internal/api/configs_test.go index 13bfb1b499..87ca9b3a1b 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/shardmap" "github.com/GetStream/Vision-Agents/acceleration/internal/store" "github.com/GetStream/Vision-Agents/acceleration/internal/stt" @@ -2424,6 +2426,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 1463229934..727acb9476 100644 --- a/acceleration/internal/api/connection_tools.go +++ b/acceleration/internal/api/connection_tools.go @@ -21,6 +21,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/none" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sensitive" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) @@ -765,7 +766,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 (sensitive.ConfigComplaint). + // binding beside a sensitive connector against (sensitive.ConfigComplaint), with each + // tool's digest as a grant made from this list pins it (sensitive.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) @@ -777,7 +779,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 && !sensitive.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/connectors.go b/acceleration/internal/api/connectors.go index 95d6d01bc4..c35c6781c9 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."` @@ -153,7 +182,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. // // Its limits are core's (core.CustomIDPattern and the rest) and the store's for the sync hash, // which TransformSchema writes into the schema, so an imported definition is held to the same @@ -164,7 +193,8 @@ type CustomConnectorRequest struct { Name string `json:"name" minLength:"1"` Category string `json:"category,omitempty"` Description string `json:"description,omitempty"` - Endpoint string `json:"endpoint" 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" 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" uniqueItems:"true" doc:"The scopes a consent asks for, each an RFC 6749 scope token."` Client *ConnectorClient `json:"client,omitempty"` @@ -174,7 +204,7 @@ type CustomConnectorRequest struct { } 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 properties := schema.Properties @@ -190,6 +220,63 @@ func (*CustomConnectorRequest) TransformSchema(_ huma.Registry, schema *huma.Sch 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. @@ -253,8 +340,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" + @@ -340,7 +427,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 { @@ -422,8 +509,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) { @@ -442,13 +532,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 @@ -459,6 +560,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 @@ -485,6 +600,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)} @@ -503,6 +622,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 185dc96788..35454cbd40 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)) } @@ -181,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) @@ -208,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) @@ -217,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) } } @@ -953,6 +959,334 @@ 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. 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)) + + 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", "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{}, + "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", + "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"}, + }, + }}, + }, + } +} + +// 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 { @@ -998,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") +} 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() { diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index 566eb08621..ff07005a57 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -241,6 +241,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_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, + "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 definition with oauth2_client_credentials, from before custom connectors lost it, is left out // and named, an export row and a change alike; every other line is written. func (s *DataMoveSuite) TestAnImportNamesTheClientCredentialsDefinitionsItLeftOut() { diff --git a/acceleration/internal/api/session_connectors_test.go b/acceleration/internal/api/session_connectors_test.go index e227e86b6b..c733daf881 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 b85825f109..e4f789fca8 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,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`, `sensitive.ConfigComplaint`). +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 | | --- | --- | --- | | 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` | @@ -164,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`) 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/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/custom.go b/acceleration/internal/connectors/core/custom.go index 22e14469af..1121a116c7 100644 --- a/acceleration/internal/connectors/core/custom.go +++ b/acceleration/internal/connectors/core/custom.go @@ -1,6 +1,7 @@ package core import ( + "context" "encoding/json" "errors" "fmt" @@ -9,11 +10,13 @@ import ( "strings" "unicode/utf8" + "github.com/GetStream/Vision-Agents/acceleration/internal/egress" "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 @@ -21,9 +24,31 @@ 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 +} + +// 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 } // The limits on a custom connector, which the API's request schema documents @@ -88,13 +113,15 @@ func (c CustomConnector) checkLimits() error { } // 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) { if err := c.checkLimits(); err != nil { return Manifest{}, err @@ -111,8 +138,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")) } @@ -129,6 +156,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 } @@ -140,9 +185,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 @@ -160,7 +210,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 index fb6ffeb91a..77a17b7f5c 100644 --- a/acceleration/internal/connectors/core/custom_test.go +++ b/acceleration/internal/connectors/core/custom_test.go @@ -1,6 +1,7 @@ package core import ( + "encoding/json" "fmt" "strings" "testing" @@ -8,6 +9,200 @@ import ( "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") +} + // CustomConnectorSuite holds CustomManifest to the limits the API's request schema documents, // each at the limit and one past it. A length is counted in characters, so a name of é, two // bytes each, is at the limit with as many é as the limit. @@ -85,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/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 new file mode 100644 index 0000000000..36a0c92e7f --- /dev/null +++ b/acceleration/internal/connectors/core/http_tools.go @@ -0,0 +1,212 @@ +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 +// 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 + // (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 + // (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 +) + +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 (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 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) { + 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") + } + 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 + // 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) + } + 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 !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") + } + 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) + } + } + } +} + +// 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..93a7755dad --- /dev/null +++ b/acceleration/internal/connectors/core/http_tools_test.go @@ -0,0 +1,246 @@ +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) }), + "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) }), + "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"}}}}, + } { + 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 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`}, + "a name of 65": {withTool(func(t *HTTPTool) { t.Parameters[strings.Repeat("p", 65)] = HTTPParameter{Type: "string"} }), `is not 1 to 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`}, + "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`}, + "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`}, + "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`}, + "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()}}}}, + `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) + } +} + +// 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 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", 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) +} + +// 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 fbb05015ce..46bfd38f01 100644 --- a/acceleration/internal/connectors/core/manifest.go +++ b/acceleration/internal/connectors/core/manifest.go @@ -119,9 +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 -// (ConfigComplaint, internal/connectors/sensitive; listConnectionTools, +// 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 (ConfigComplaint, internal/connectors/sensitive; 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 // among them: a consent shows the pinned name (ConnectorConsents, internal/api/authorizations.go). @@ -136,6 +136,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 +288,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 +300,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 +825,19 @@ func (m Manifest) Validate() error { fail(field+".needs_scopes", "is required: a tool that needs no scope is left out") } } + 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) + // 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) + } 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/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..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() { @@ -93,6 +100,22 @@ 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)) +} + +// 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 b322c250fd..8767b55f92 100644 --- a/acceleration/internal/connectors/core/scheme.go +++ b/acceleration/internal/connectors/core/scheme.go @@ -55,6 +55,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/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/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..3be426c405 --- /dev/null +++ b/acceleration/internal/connectors/fakeprovider/api.go @@ -0,0 +1,81 @@ +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; 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) + 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.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 + } + _, _ = 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..54adf5bdb0 100644 --- a/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go +++ b/acceleration/internal/connectors/fakeprovider/fakeprovider_test.go @@ -1170,3 +1170,53 @@ 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()) + 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) + 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) + contentType = response.Header.Get("Content-Type") + 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) + 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") + 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/sensitive/AGENTS.md b/acceleration/internal/connectors/sensitive/AGENTS.md index 0fd14ce6bb..ab9b344e97 100644 --- a/acceleration/internal/connectors/sensitive/AGENTS.md +++ b/acceleration/internal/connectors/sensitive/AGENTS.md @@ -6,6 +6,6 @@ The rule that keeps a connector whose manifest says `sensitive: true` (its tools - An import (`POST /v1/data/import`, `router replicate`) calls both through `store.SetConfigRule`, which `openStore` (`cmd/router`) sets, since `internal/store` cannot import this package. It weighs each config it writes and each set that config is part of inside the import's transaction: an export row once that row is written, and a page of changes once the whole page is written. A config that breaks the rule refuses the row or the whole page, naming it as `agent_configs:{"id":…}`. An export carries agent configs before connector definitions, so a connector definition the import writes weighs again, in the same transaction, each live config of the app that binds it, and refuses as `connector_definitions:{"id":…,"revision":…}`. - `GraphComplaint` checks a parent and its child agents as one config. A parent hands its input to each child and reads each answer, so what one reads may reach any other, a sibling's tools included. Config writes call it (`sensitiveGraphComplaint`, `internal/api/child_agents.go`) over the config with its children and over each parent that calls the config with all of that parent's children, so a set that breaks it is a 400 naming the agents, the bindings and the connector, even for a save that changes another field. `childRunner.Run` (`internal/session/child_agents.go`) calls it on every delegation, with the parent as it runs and each child as stored now, and refuses a delegation that breaks it with a tool error the model reads: it covers a set stored before the writes checked it. -It lives here, not in `internal/api`, because `internal/api` imports `internal/session`, and both need it. It reads only the store and the manifest model. +It lives here, not in `internal/api`, because `internal/api` imports `internal/session`, and both need it. It reads only the store and the manifest model, and an http tool's schema digest (`GrantSendsOut`, `sources/http`): an http tool only reads at the digest its grant pins. Check: `go test -tags integration -run 'TestChildAgentsSuite/(TestADelegation|TestAWrite|TestASession|TestARun)|TestConfigsSuite/TestNessy|TestDataMoveSuite/(TestAnImported|TestAChangedChild|TestImportedAgents)' ./internal/api` and `go test -tags integration -run 'TestReplicateRepeatSuite/(TestAPage|TestAFirstCopy)' ./cmd/router`. diff --git a/acceleration/internal/connectors/sensitive/sensitive.go b/acceleration/internal/connectors/sensitive/sensitive.go index e646536eb5..11be101088 100644 --- a/acceleration/internal/connectors/sensitive/sensitive.go +++ b/acceleration/internal/connectors/sensitive/sensitive.go @@ -11,6 +11,7 @@ import ( "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" ) @@ -141,13 +142,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/connectors/sources/http/AGENTS.md b/acceleration/internal/connectors/sources/http/AGENTS.md new file mode 100644 index 0000000000..d68ac97900 --- /dev/null +++ b/acceleration/internal/connectors/sources/http/AGENTS.md @@ -0,0 +1,69 @@ +# 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. 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 + +``` +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 "__" + 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; 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 + 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 + 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. 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`. +- **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`. + +A grant reads only at its digest: `internal/connectors/sensitive` judges an http tool read_only (`GrantSendsOut`, for a config saved beside a sensitive connector, for a delegation to child agents, and for `internal/api`'s listing of a connection's tools) 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. `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/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/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 new file mode 100644 index 0000000000..ffe2880c38 --- /dev/null +++ b/acceleration/internal/connectors/sources/http/source.go @@ -0,0 +1,244 @@ +// 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 + } + // 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 + } + 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, 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) + 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..9a30d030cb --- /dev/null +++ b/acceleration/internal/connectors/sources/http/source_test.go @@ -0,0 +1,1011 @@ +package http + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "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", 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"}, + }} + + 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", 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"}, + }} + + _, 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", 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) + + 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) + } +} + +// 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) +} + +// 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", Description: "Calls the API.", 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", + "/reason-own": "The API answered 403 Forbidden", + "/reason-unknown": "The API answered 499", + } { + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", 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", 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)) +} + +// 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", 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, `{}`) + + s.Require().NoError(err, tool.Method) + s.Equal(want, llm.TextOf(result.Parts), tool.Method) + } +} + +func (s *SourceSuite) TestAToolErrorOverTheCapIsCutWithTheMarker() { + tool := core.HTTPTool{Name: "get", Description: "Calls the API.", 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", Description: "Calls the API.", 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", Description: "Calls the API.", 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", Description: "Calls the API.", 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", Description: "Calls the API.", 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", Description: "Calls the API.", 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", 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") + + 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", Description: "Calls the API.", 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", Description: "Calls the API.", 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", Description: "Calls the API.", 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", 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) + + 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", Description: "Calls the API.", 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 "/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") + 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") + } +} + +// 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 { + 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..7be298f48e --- /dev/null +++ b/acceleration/internal/connectors/sources/http/toolset.go @@ -0,0 +1,277 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "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} + +// 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 { + 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, 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 { + 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 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) + defer cancel() + } + // 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 + } + 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 + } + // 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 := "The API answered " + status(response) + if len(body) > 0 { + message += ": " + text + } + // 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("The API answered " + status(response) + ".")}, 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). +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 (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) { + 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)) { + 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 +} + +// 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.go b/acceleration/internal/store/datamove.go index 36339ac2c6..4e07a7a3a0 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -695,6 +695,10 @@ func (s *Store) ImportRow(ctx context.Context, customerID, table string, row jso return err } spec, _ := dataTableByName(table) + row, err := importableRow(ctx, customerID, table, row) + if err != nil { + return err + } var stale []string if table == "phone_numbers" || table == "connector_definitions" { // A number is checked against who else holds it under a lock its write has to keep @@ -711,7 +715,7 @@ func (s *Store) ImportRow(ctx context.Context, customerID, table string, row jso if !readCached(table) { return s.importRow(ctx, s.sideOf(spec), customerID, table, row, &stale) } - err := s.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + err = s.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error { if err := s.importRow(ctx, tx, customerID, table, row, &stale); err != nil || table != "agent_configs" { return err } @@ -735,8 +739,30 @@ 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) + } + // Unchecked: importRow leaves it out. + if SkippedRow(table, row) != "" { + return row, nil + } + 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 @@ -774,19 +800,9 @@ 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 SkippedRow(table, row) != "" { - return nil - } - if row, err = importableDefinition(row); err != nil { - return err - } + // The row importableRow let through unchecked. + if SkippedRow(table, row) != "" { + return nil } shape, err := s.shapeOf(ctx, table) if err != nil { @@ -1990,8 +2006,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 @@ -2010,6 +2027,13 @@ 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) @@ -2346,6 +2370,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 || change.Skipped() { + continue + } + payload, err := importableRow(ctx, customerID, change.Table, change.Payload) + if err != nil { + return err + } + changes[i].Payload = payload + } var stale, left []string _, err := s.cachedWrite(ctx, db, func(ctx context.Context, tx bun.Tx) error { if err := lockNumbers(ctx, tx, changes); err != nil { diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index f7bcae6ae2..7630442547 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -3048,6 +3048,85 @@ 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, 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}}}]}]}` + +// 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, "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_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) + + 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_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, + 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() { + 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() { diff --git a/acceleration/internal/store/datamove_unit_test.go b/acceleration/internal/store/datamove_unit_test.go index 57cc6e507a..0022c884b0 100644 --- a/acceleration/internal/store/datamove_unit_test.go +++ b/acceleration/internal/store/datamove_unit_test.go @@ -1,13 +1,82 @@ package store import ( + "context" "encoding/json" "strings" "testing" "github.com/stretchr/testify/require" + "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)) +} + +// 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"])) + } +} + +// 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) + + _, 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) + } +} + +// 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 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+`}`)) + + s.ErrorIs(err, ErrNotACustomConnector, name) + } +} + // definitionRow is a connector_definitions row of custom_acme as an export carries it, with // extra, JSON members, added or written over, and the manifest's own members manifest. func definitionRow(extra, manifest string) json.RawMessage { @@ -23,7 +92,7 @@ func columnOf(t *testing.T, row json.RawMessage, column string) any { } func TestAnImportedDefinitionPastAnAPILimitIsRefused(t *testing.T) { - _, err := importableDefinition(definitionRow("", `"schemes": ["bearer"], "description": "`+strings.Repeat("é", 1001)+`"`)) + _, err := importableDefinition(context.Background(), definitionRow("", `"schemes": ["bearer"], "description": "`+strings.Repeat("é", 1001)+`"`)) require.ErrorIs(t, err, ErrNotACustomConnector) require.ErrorContains(t, err, `"custom_acme"`) @@ -37,7 +106,7 @@ func TestAnImportedDefinitionsColumnsAreItsManifests(t *testing.T) { row := definitionRow(`, "name": "`+long+`", "category": "`+long+`", "description": "`+long+`"`, `"schemes": ["bearer"], "category": "CRM", "description": "Acme's CRM"`) - written, err := importableDefinition(row) + written, err := importableDefinition(context.Background(), row) require.NoError(t, err) require.Equal(t, "Acme", columnOf(t, written, "name")) @@ -47,11 +116,11 @@ func TestAnImportedDefinitionsColumnsAreItsManifests(t *testing.T) { func TestAnImportedDefinitionsSyncHashIsPrintableASCIIOfAtMost128(t *testing.T) { for _, hash := range []string{`""`, `null`, `"` + strings.Repeat("!~", 64) + `"`} { - _, err := importableDefinition(definitionRow(`, "sync_hash": `+hash, `"schemes": ["bearer"]`)) + _, err := importableDefinition(context.Background(), definitionRow(`, "sync_hash": `+hash, `"schemes": ["bearer"]`)) require.NoError(t, err, hash) } for _, hash := range []string{`"` + strings.Repeat("a", 129) + `"`, `"a b"`, `"a\u0000"`, `"é"`, `12`, `["a"]`} { - _, err := importableDefinition(definitionRow(`, "sync_hash": `+hash, `"schemes": ["bearer"]`)) + _, err := importableDefinition(context.Background(), definitionRow(`, "sync_hash": `+hash, `"schemes": ["bearer"]`)) require.ErrorIs(t, err, ErrInvalidImport, hash) require.ErrorContains(t, err, "sync_hash is not printable ASCII without a space of at most 128 characters", hash) } @@ -65,7 +134,7 @@ func TestAnImportedDefinitionWithoutASyncHashIsImportable(t *testing.T) { row, err := json.Marshal(fields) require.NoError(t, err) - _, err = importableDefinition(row) + _, err = importableDefinition(context.Background(), row) require.NoError(t, err) } 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 f47b922232..3901101e77 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py @@ -214,6 +214,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 @@ -242,6 +244,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 @@ -889,6 +897,8 @@ "ConnectorSandbox", "ConnectorSetup", "ConnectorSetupStep", + "ConnectorSource", + "ConnectorSourceKind", "ConnectorToolGrant", "Contact", "ContactAttempt", @@ -917,6 +927,12 @@ "CreditEntryKind", "CreditPage", "CustomConnectorRequest", + "CustomHTTPAPI", + "CustomHTTPParameter", + "CustomHTTPParameterType", + "CustomHTTPTool", + "CustomHTTPToolMethod", + "CustomHTTPToolParameters", "CustomModel", "CustomModelPage", "CustomModelRequest", 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/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 74c2534f08..d6e59d94b5 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,22 +18,23 @@ @_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. sync_hash (str | Unset): The fingerprint of the file this definition was synced from, which the connector then carries. Absent for a write that is no sync: the connector then carries none. Sending a definition the newest revision already says with another hash stores no new revision and records the hash on that one. @@ -42,20 +44,19 @@ class CustomConnectorRequest: stores the next revision, as a sync that means to write over the edit wants. """ - 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 sync_hash: str | Unset = UNSET check_changes: bool | Unset = UNSET def to_dict(self) -> dict[str, Any]: - endpoint = self.endpoint - id = self.id name = self.name @@ -67,6 +68,8 @@ def to_dict(self) -> dict[str, Any]: else: schemes = self.schemes + endpoint = self.endpoint + category = self.category client: dict[str, Any] | Unset = UNSET @@ -84,6 +87,10 @@ 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() + sync_hash = self.sync_hash check_changes = self.check_changes @@ -92,12 +99,13 @@ def to_dict(self) -> 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: @@ -106,6 +114,8 @@ 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 if sync_hash is not UNSET: field_dict["sync_hash"] = sync_hash if check_changes is not UNSET: @@ -116,10 +126,9 @@ def to_dict(self) -> dict[str, Any]: @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") @@ -139,6 +148,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) @@ -167,19 +178,27 @@ 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) + sync_hash = d.pop("sync_hash", UNSET) check_changes = d.pop("check_changes", UNSET) custom_connector_request = cls( - endpoint=endpoint, id=id, name=name, schemes=schemes, + endpoint=endpoint, category=category, client=client, description=description, scopes=scopes, + http=http, sync_hash=sync_hash, check_changes=check_changes, ) 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 aa5ff760fa..3af9ddbf68 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -5387,6 +5387,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. /// @@ -6087,6 +6093,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. /// @@ -7098,7 +7116,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 @@ -7120,10 +7138,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. @@ -7154,6 +7178,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..058f5c464d 100644 --- a/sdks/go/acceleration/enums_test.go +++ b/sdks/go/acceleration/enums_test.go @@ -24,3 +24,53 @@ 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) + } + } +} + +// 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 e7807135cc..d84ba5d209 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" @@ -1099,6 +1117,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" @@ -5833,6 +5905,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"` } @@ -6127,6 +6202,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. @@ -6558,7 +6642,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"` @@ -6569,8 +6653,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"` @@ -6586,6 +6673,49 @@ type CustomConnectorRequest struct { SyncHash *string `json:"sync_hash,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"` @@ -14200,9 +14330,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. // @@ -14211,9 +14341,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. // @@ -18401,9 +18531,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. // @@ -18422,9 +18552,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. // @@ -37715,9 +37845,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. // @@ -37726,9 +37856,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. // @@ -69751,9 +69881,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. // @@ -69768,9 +69898,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 7b9fb3947d..60e248cd2f 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. */ @@ -6634,6 +6634,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; }; @@ -6895,6 +6897,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. */ @@ -7258,15 +7269,17 @@ 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; /** @description Refuse the create, with unsynced_changes (409), when the newest revision of the id carries no sync_hash, because no sync wrote it, and says something else than this definition: a sync would write over an edit made outside it, in the dashboard, say. The same definition is not refused. Omitted, the create stores the next revision, as a sync that means to write over the edit wants. */ readonly check_changes?: boolean; 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; @@ -7277,6 +7290,38 @@ export type components = { /** @description The fingerprint of the file this definition was synced from, which the connector then carries. Absent for a write that is no sync: the connector then carries none. Sending a definition the newest revision already says with another hash stores no new revision and records the hash on that one. */ readonly sync_hash?: string; }; + /** @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/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 @@ + */ 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, // The fingerprint of the file this definition was synced from, which the connector then carries. Absent for a... public ?string $syncHash = null, // Refuse the create, with unsynced_changes (409), when the newest revision of the id carries no sync_hash, be... @@ -42,14 +44,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, syncHash: array_key_exists('sync_hash', $data) && $data['sync_hash'] !== null ? Json::string($data, 'sync_hash') : null, checkChanges: array_key_exists('check_changes', $data) && $data['check_changes'] !== null ? Json::bool($data, 'check_changes') : null, ); @@ -63,10 +66,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; } @@ -79,6 +84,9 @@ public function toArray(): array if ($this->scopes !== null) { $out['scopes'] = $this->scopes; } + if ($this->http !== null) { + $out['http'] = $this->http->toArray(); + } if ($this->syncHash !== null) { $out['sync_hash'] = $this->syncHash; } 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 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, diff --git a/sdks/rust/src/operations.rs b/sdks/rust/src/operations.rs index 9e8becfa50..9958f665c6 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 796c271cb3..7b9f95a0b9 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -4070,6 +4070,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>, @@ -4712,6 +4714,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 { @@ -5318,7 +5372,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)] @@ -5332,8 +5386,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, @@ -5347,6 +5405,165 @@ pub struct CustomConnectorRequest { #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub sync_hash: ::std::option::Option<::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 {