diff --git a/.claude/skills/add-connector/SKILL.md b/.claude/skills/add-connector/SKILL.md index d72c844022..e35e6fb904 100644 --- a/.claude/skills/add-connector/SKILL.md +++ b/.claude/skills/add-connector/SKILL.md @@ -16,11 +16,15 @@ First decide which kind you need. Connecting an existing connector to an agent i ## A custom connector Dashboard: **Library › Connectors › New connector**. API: `POST /v1/agents/connectors` -(`CustomConnectorRequest`: `id`, `name`, `endpoint`, `schemes`, optional `scopes`, +(`CustomConnectorRequest`: `id`, `name`, `endpoint` or `http`, `schemes`, optional `scopes`, `client`, `category`, `description`). - The id starts with `custom_`, for example `custom_crm`. Built-ins never use that prefix. - `endpoint` is the MCP server's https URL. +- `http` is an HTTP API in place of an MCP server: `base_url` and `tools`, each tool with + `name`, `description`, `method`, `path`, `parameters` and `read_only` (only on a GET or a + HEAD). Send `endpoint` or `http`, not both. `base_url` must be a public https URL, and it is + never shown again. `oauth2_code` is not available for one. - `schemes` is how a connection signs in: `oauth2_code`, `bearer`, `api_key`, or `none`. - A public server that needs no credential takes `schemes: ["none"]`. Create the connection, then connect it with `PUT /v1/agents/connections/{id}/credentials` and the body diff --git a/.claude/skills/connectors/SKILL.md b/.claude/skills/connectors/SKILL.md index f86b2b622e..ce8d29a9f3 100644 --- a/.claude/skills/connectors/SKILL.md +++ b/.claude/skills/connectors/SKILL.md @@ -65,7 +65,7 @@ The same with the API (operations in `acceleration/api/openapi.yaml`): |---|---| | The catalog | `GET /v1/agents/connectors` | | The app's own OAuth client | `PUT /v1/agents/connectors/{id}/oauth-client` | -| A custom MCP connector | `POST /v1/agents/connectors` (`id` starts with `custom_`) | +| A custom MCP or HTTP API connector | `POST /v1/agents/connectors` (`id` starts with `custom_`; `endpoint` or `http`) | | A connection | `POST /v1/agents/connections` (`connector_id`, `owner`, `auth_scheme`) | | OAuth consent | `POST /v1/agents/connections/{id}/authorizations` → open `launch_url` in a popup | | A token or key | `PUT /v1/agents/connections/{id}/credentials` | diff --git a/.claude/skills/sdk/notes/2026-11-24-ai-3676.md b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md new file mode 100644 index 0000000000..75c3fcf685 --- /dev/null +++ b/.claude/skills/sdk/notes/2026-11-24-ai-3676.md @@ -0,0 +1 @@ +`createConnector` (`POST /v1/agents/connectors`) takes an HTTP API in place of an MCP server (AI-3676). `CustomConnectorRequest` has a new optional `http`, a `CustomHTTPAPI` `{base_url, tools}`. Each tool is a `CustomHTTPTool` `{name, description, method, path, parameters, read_only}`: `method` is one of `GET`, `HEAD`, `POST`, `PUT`, `PATCH` and `DELETE`, and `parameters` maps a name to a `CustomHTTPParameter` `{type, description, required}`, whose `type` is one of `string`, `number`, `integer` and `boolean`. `endpoint` is no longer required: a request sends a non-empty `endpoint` or `http`, not both. This breaks existing callers in four SDKs. In Go, `CustomConnectorRequest.Endpoint` is now a `*string` (`sdks/go/acceleration/generated.go`), and a caller that set it as a string now sets a pointer. In Rust, `CustomConnectorRequest.endpoint` is now an `Option` (`sdks/rust/src/types.rs`), so a struct literal or a read of a `String` no longer compiles. In PHP (`sdks/php/src/Generated/CustomConnectorRequest.php`) and Python (`plugins/stream`, `_generated/models/custom_connector_request.py`), `endpoint` moves from the first constructor argument to after `schemes`, so a positional call no longer matches; named and keyword arguments still work. The `Connector` the router answers is unchanged, so it shows neither `base_url` nor the tools. Go, JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP have the regenerated clients. Other SDKs need to update: a `connectors.create` resource method, where an SDK has one, takes `http` beside `endpoint`. Swift, Kotlin and Dart need nothing, since `createConnector` is not client-accessible. diff --git a/CHANGELOG.md b/CHANGELOG.md index c64ab679e0..625be5cdcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -710,6 +710,15 @@ Every reply the agent abandons logs one INFO line, `the agent was interrupted`, ## Breaking Changes +### `CustomConnectorRequest`'s endpoint is optional in the Go, Rust, PHP and Python SDKs + +`POST /v1/agents/connectors` now takes either an MCP `endpoint` or an `http` block with a `base_url` and its tools, so `endpoint` is optional in every generated `CustomConnectorRequest` (AI-3676): + +- Go: `CustomConnectorRequest.Endpoint` is now `*string`. Set it with a pointer (for example `Endpoint: &url`); a caller that set a plain string no longer compiles. +- Rust: `CustomConnectorRequest.endpoint` is now `Option`. Set it with `Some(url)`; a struct literal with a plain `String`, or a read of one, no longer compiles. +- PHP: the `CustomConnectorRequest` constructor takes `$endpoint` after `$schemes`, not first. A positional call no longer matches; named arguments work as before. +- Python (`plugins/stream`): the generated `CustomConnectorRequest` takes `endpoint` after `schemes`, not first. A positional call no longer matches; keyword arguments work as before. + ### The Go SDK reads no items for a turn with no id `AgentResponse.Items`, on the handle `Responses.Create` returns, fails with `client.ErrUnnamedTurn` when the turn has no id: the router names none for an incognito session, a speech-to-speech session or the retry of a `request_id` already taken. It used to read every turn in the session instead, passed off as this turn's; a caller that relied on that now gets the error, and reads `Session.Responses.Items` for the whole session or follows `Session.Events` (AI-3571). diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index 02e352415b..908ad78130 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -4652,7 +4652,7 @@ components: type: object CustomConnectorRequest: additionalProperties: false - description: A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. + description: A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. properties: category: maxLength: 80 @@ -4663,9 +4663,12 @@ components: maxLength: 1000 type: string endpoint: - description: 'The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused.' + description: 'The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both.' maxLength: 2048 type: string + http: + $ref: '#/components/schemas/CustomHTTPAPI' + description: An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. id: description: Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. pattern: ^custom_[a-z][a-z0-9_]{0,56}$ @@ -4695,9 +4698,99 @@ components: required: - id - name - - endpoint - schemes type: object + CustomHTTPAPI: + additionalProperties: false + description: An HTTP API a custom connector calls, and the tools it offers an agent. + properties: + base_url: + description: 'The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored.' + maxLength: 2048 + type: string + tools: + description: At least one and at most 128, each name once. + items: + $ref: '#/components/schemas/CustomHTTPTool' + maxItems: 128 + minItems: 1 + type: array + required: + - base_url + - tools + type: object + CustomHTTPParameter: + additionalProperties: false + description: One value the model gives an http tool. + properties: + description: + maxLength: 1000 + type: string + required: + description: The model must give it. A parameter in the path must be required. + type: boolean + type: + enum: + - string + - number + - integer + - boolean + type: string + x-enum-varnames: + - CustomHTTPParameterTypeString + - CustomHTTPParameterTypeNumber + - CustomHTTPParameterTypeInteger + - CustomHTTPParameterTypeBoolean + required: + - type + type: object + CustomHTTPTool: + additionalProperties: false + description: 'One tool of an http connector: one request, whose method and path are fixed.' + properties: + description: + description: What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + maxLength: 1000 + type: string + method: + enum: + - GET + - HEAD + - POST + - PUT + - PATCH + - DELETE + type: string + x-enum-varnames: + - CustomHTTPToolMethodGET + - CustomHTTPToolMethodHEAD + - CustomHTTPToolMethodPOST + - CustomHTTPToolMethodPUT + - CustomHTTPToolMethodPATCH + - CustomHTTPToolMethodDELETE + name: + description: 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + pattern: ^[A-Za-z0-9_-]{1,63}$ + type: string + parameters: + additionalProperties: + $ref: '#/components/schemas/CustomHTTPParameter' + description: The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + maxProperties: 64 + type: object + path: + description: Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + maxLength: 2048 + type: string + read_only: + description: The tool only reads. Only a GET or HEAD tool may say so. + type: boolean + required: + - name + - description + - method + - path + type: object CustomModel: properties: base_url: @@ -16243,7 +16336,7 @@ paths: summary: List or search connectors post: description: |- - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. operationId: createConnector @@ -16281,7 +16374,7 @@ paths: $ref: '#/components/responses/InternalError' "503": $ref: '#/components/responses/Unavailable' - summary: Add a custom MCP connector + summary: Add a custom connector /v1/agents/connectors/{id}: delete: description: |- diff --git a/acceleration/internal/api/connectors.go b/acceleration/internal/api/connectors.go index 9375c644eb..c6e695bc76 100644 --- a/acceleration/internal/api/connectors.go +++ b/acceleration/internal/api/connectors.go @@ -152,7 +152,7 @@ type ConnectorPage struct { NextCursor *string `json:"next_cursor,omitempty" doc:"Pass as cursor for the next page, with the same q. Absent on the last one."` } -// CustomConnectorRequest is a custom MCP server for the app's agents to connect to. +// CustomConnectorRequest is a custom MCP server or HTTP API for the app's agents to connect to. // // The limits on name, category and description are the prototype's // (CreateConnectorDefinitionRequest in api/openapi.yaml on codex/connector-support at @@ -168,19 +168,77 @@ type CustomConnectorRequest struct { Name string `json:"name" minLength:"1" maxLength:"120"` Category string `json:"category,omitempty" maxLength:"80"` Description string `json:"description,omitempty" maxLength:"1000"` - Endpoint string `json:"endpoint" maxLength:"2048" doc:"The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused."` + Endpoint string `json:"endpoint,omitempty" maxLength:"2048" doc:"The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both."` + HTTP *CustomHTTPAPI `json:"http,omitempty" doc:"An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both."` Schemes []string `json:"schemes" minItems:"1" doc:"How a connection may authenticate. Each must be a scheme this deployment has, except oauth2_client_credentials, which a custom connector cannot use: it needs a token endpoint a custom connector cannot set."` Scopes []string `json:"scopes,omitempty" maxItems:"100" uniqueItems:"true" pattern:"^[!#-\\[\\]-~]+$" patternDescription:"an RFC 6749 scope token" doc:"The scopes a consent asks for, each an RFC 6749 scope token."` Client *ConnectorClient `json:"client,omitempty"` } func (*CustomConnectorRequest) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { - schema.Description = "A custom MCP server for the app's agents to connect to. An unknown " + + schema.Description = "A custom MCP server or HTTP API for the app's agents to connect to. An unknown " + "field is refused rather than ignored." schema.AdditionalProperties = false return schema } +// CustomHTTPAPI is an http connector's API and its tools (core.CustomConnector's BaseURL and +// Tools). The schema carries the caps and the tool name pattern of core.Manifest.Validate +// (maxHTTPTools, maxHTTPToolDescription, maxHTTPPath, maxHTTPParameters and httpToolName in +// internal/connectors/core/http_tools.go), so a request breaking one fails validation. Huma +// counts a length in characters and core in bytes, so core still refuses a description whose +// characters fit and bytes do not. The other rules are core's alone (checkHTTPSource), which +// answer naming the tool. +type CustomHTTPAPI struct { + BaseURL string `json:"base_url" maxLength:"2048" doc:"The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored."` + Tools []CustomHTTPTool `json:"tools" nullable:"false" minItems:"1" maxItems:"128" doc:"At least one and at most 128, each name once."` +} + +func (*CustomHTTPAPI) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "An HTTP API a custom connector calls, and the tools it offers an agent." + schema.AdditionalProperties = false + return schema +} + +// CustomHTTPTool is one tool of an http connector (core.HTTPTool). Its methods and parameter +// types are core's (httpMethods and httpParameterTypes in internal/connectors/core/http_tools.go). +type CustomHTTPTool struct { + Name string `json:"name" pattern:"^[A-Za-z0-9_-]{1,63}$" doc:"1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __."` + Description string `json:"description" maxLength:"1000" doc:"What the tool does, which the model reads to know when to use it. Up to 1000 bytes."` + Method string `json:"method" enum:"GET,HEAD,POST,PUT,PATCH,DELETE"` + Path string `json:"path" maxLength:"2048" doc:"Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required."` + Parameters map[string]CustomHTTPParameter `json:"parameters,omitempty" maxProperties:"64" doc:"The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused."` + ReadOnly bool `json:"read_only,omitempty" doc:"The tool only reads. Only a GET or HEAD tool may say so."` +} + +func (*CustomHTTPTool) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One tool of an http connector: one request, whose method and path are fixed." + schema.AdditionalProperties = false + // Named, so the next enum with one of these values does not rename the Go SDK's constants, + // as ConnectionOwnerType's are (connections.go). + schema.Properties["method"].Extensions = map[string]any{"x-enum-varnames": []string{"CustomHTTPToolMethodGET", + "CustomHTTPToolMethodHEAD", "CustomHTTPToolMethodPOST", "CustomHTTPToolMethodPUT", "CustomHTTPToolMethodPATCH", + "CustomHTTPToolMethodDELETE"}} + return schema +} + +// CustomHTTPParameter is one value the model gives an http tool (core.HTTPParameter). +type CustomHTTPParameter struct { + Type string `json:"type" enum:"string,number,integer,boolean"` + Description string `json:"description,omitempty" maxLength:"1000"` + Required bool `json:"required,omitempty" doc:"The model must give it. A parameter in the path must be required."` +} + +func (*CustomHTTPParameter) TransformSchema(_ huma.Registry, schema *huma.Schema) *huma.Schema { + schema.Description = "One value the model gives an http tool." + schema.AdditionalProperties = false + // InvocationArgumentType has string, number and boolean too: unnamed, oapi-codegen would + // prefix both enums' constants (enumsConflict), renaming the Go SDK's String, Number and the rest. + schema.Properties["type"].Extensions = map[string]any{"x-enum-varnames": []string{"CustomHTTPParameterTypeString", + "CustomHTTPParameterTypeNumber", "CustomHTTPParameterTypeInteger", "CustomHTTPParameterTypeBoolean"}} + return schema +} + type listConnectorsRequest struct { // 120 is the longest name a custom definition may have, which is what a picker's // search box looks for. @@ -244,8 +302,8 @@ func (s *Server) registerConnectors(api huma.API) { OperationID: "createConnector", Method: http.MethodPost, Path: "/v1/agents/connectors", - Summary: "Add a custom MCP connector", - Description: "Stores a custom MCP server as one of the app's connectors. Sending an " + + Summary: "Add a custom connector", + Description: "Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an " + "id the app already has stores its next revision, which connections pick up when " + "they reconnect; sending the same definition again changes nothing. A built-in " + "cannot be changed this way.\n\n" + @@ -331,7 +389,7 @@ func (s *Server) getConnector(ctx context.Context, request *getConnectorRequest) return &connectorResponse{Body: connectorOf(definition, s.publicURL)}, nil } -// createConnector stores a custom MCP definition as the caller's own. +// createConnector stores a custom MCP or http definition as the caller's own. func (s *Server) createConnector(ctx context.Context, request *createConnectorRequest) (*connectorResponse, error) { customerID, ok := CustomerFrom(ctx) if !ok { @@ -409,8 +467,11 @@ func namedFew(names []string) string { return fmt.Sprintf("%s and %d more", strings.Join(names[:usesNamed], ", "), len(names)-usesNamed) } -// customManifest is the manifest a custom MCP definition is stored as, or why it cannot be. +// customManifest is the manifest a custom MCP or http definition is stored as, or why it cannot be. func (s *Server) customManifest(ctx context.Context, sent CustomConnectorRequest) (core.Manifest, error) { + if (sent.Endpoint == "") == (sent.HTTP == nil) { + return core.Manifest{}, stack.Wrap(errors.New("a custom connector has an MCP endpoint or an http API, and exactly one of them")) + } known := slices.Sorted(maps.Keys(s.connectors.Schemes)) for _, scheme := range sent.Schemes { if !slices.Contains(known, scheme) { @@ -429,13 +490,24 @@ func (s *Server) customManifest(ctx context.Context, sent CustomConnectorRequest client.AuthMethod = core.ClientAuthMethod(sent.Client.AuthMethod) client.Alg = sent.Client.Alg } - manifest, err := core.CustomManifest(core.CustomConnector{ + custom := core.CustomConnector{ ID: sent.ID, Name: sent.Name, Category: sent.Category, Description: sent.Description, Endpoint: sent.Endpoint, Schemes: sent.Schemes, Scopes: sent.Scopes, Client: client, - }) + } + if sent.HTTP != nil { + // Before the manifest's rules, so every base_url refused gets one answer. + if err := core.CheckBaseURL(ctx, sent.HTTP.BaseURL); err != nil { + return core.Manifest{}, err + } + custom.BaseURL, custom.Tools = sent.HTTP.BaseURL, httpTools(sent.HTTP.Tools) + } + manifest, err := core.CustomManifest(custom) if err != nil { return core.Manifest{}, err } + if sent.HTTP != nil { + return manifest, nil + } // Last, since it resolves the host: the checks above cost nothing. // One answer for every refusal: egress's own errors tell a name that does not resolve from // one that resolves to a private address, which would let a caller probe the names the @@ -446,6 +518,20 @@ func (s *Server) customManifest(ctx context.Context, sent CustomConnectorRequest return manifest, nil } +// httpTools is sent as core's tools, field by field. +func httpTools(sent []CustomHTTPTool) []core.HTTPTool { + tools := make([]core.HTTPTool, 0, len(sent)) + for _, tool := range sent { + parameters := make(map[string]core.HTTPParameter, len(tool.Parameters)) + for name, parameter := range tool.Parameters { + parameters[name] = core.HTTPParameter{Type: parameter.Type, Description: parameter.Description, Required: parameter.Required} + } + tools = append(tools, core.HTTPTool{Name: tool.Name, Description: tool.Description, Method: tool.Method, + Path: tool.Path, Parameters: parameters, ReadOnly: tool.ReadOnly}) + } + return tools +} + // connectorOf is the part of a stored definition a caller is shown. Each field is // copied by name, so a field added to the manifest stays hidden until it is added here. // publicURL is the router's, which an oauth2_code connector's redirect URI is built from as a diff --git a/acceleration/internal/api/connectors_test.go b/acceleration/internal/api/connectors_test.go index 113784d546..43023818f5 100644 --- a/acceleration/internal/api/connectors_test.go +++ b/acceleration/internal/api/connectors_test.go @@ -16,6 +16,8 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/providers" + "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/schemes/none" + httpsource "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/sources/http" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) @@ -29,14 +31,16 @@ func TestConnectorsSuite(t *testing.T) { runSuite(t, new(ConnectorsSuite)) } -// SetupSuite registers the scheme the built-ins name, and seeds the built-ins as a router -// start does. Seeding is idempotent, so suites running beside this one see the same rows. +// SetupSuite registers the scheme the built-ins name, none and the http source, for a +// connection to an http connector, and seeds the built-ins as a router start does. Seeding is +// idempotent, so suites running beside this one see the same rows. func (s *ConnectorsSuite) SetupSuite() { s.connectors = core.Registry{Schemes: map[string]core.Scheme{ "oauth2_code": namedScheme("oauth2_code"), "oauth2_client_credentials": namedScheme("oauth2_client_credentials"), "api_key": namedScheme("api_key"), - }} + none.Name: none.New(), + }, ToolSources: map[string]core.ToolSource{httpsource.Kind: httpsource.New()}} s.RouterSuite.SetupSuite() s.Require().NoError(s.store.ConnectorDefinitions.Seed(context.Background(), providers.FS)) } @@ -757,6 +761,291 @@ WHERE datname = current_database() AND wait_event_type = 'Lock' return count } +// TestAnMCPConnectorIsAnsweredAsBefore is the control for AI-3676: a custom MCP connector's +// create, and the refusals of its endpoint, answer as on 5a798ad5d, probed there with this +// request (AI-3676/base-probe.txt): the same keys and values, and the same messages. +func (s *ConnectorsSuite) TestAnMCPConnectorIsAnsweredAsBefore() { + id := s.customID() + status, raw := s.serverClient.call(http.MethodPost, "/v1/agents/connectors", s.customConnector(id)) + + s.Require().Equal(http.StatusOK, status) + var shown map[string]any + s.Require().NoError(json.Unmarshal(raw, &shown)) + s.Equal([]string{"channel", "client", "created_at", "custom", "duration", "id", "inputs", "name", "revision", "schemes", "scopes"}, + slices.Sorted(maps.Keys(shown))) + for _, key := range []string{"created_at", "duration"} { + delete(shown, key) + } + s.Equal(map[string]any{"channel": false, "client": map[string]any{"registration": []any{"dcr"}}, "custom": true, "id": id, + "inputs": []any{}, "name": "Our CRM", "revision": float64(1), "schemes": []any{"oauth2_code"}, "scopes": []any{}}, shown) + + for endpoint, message := range map[string]string{ + "https://10.0.0.7/mcp": "endpoint must be a public https URL without userinfo, query or fragment", + "https://8.8.8.8/mcp?x=1": "endpoint must be a public https URL without userinfo, query or fragment", + "http://8.8.8.8/mcp": `manifest "%s": endpoints.mcp: "http://8.8.8.8/mcp" does not start with https:// or a placeholder`, + } { + sent := s.customConnector(s.customID()) + sent["endpoint"] = endpoint + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, endpoint) + s.Equal(strings.ReplaceAll(message, "%s", sent["id"].(string)), failure, endpoint) + } +} + +// TestACustomHTTPConnectorIsStoredAndItsAPIIsNeverShown is AC-1 of AI-3669 through the API: +// open_meteo's file as the CLI posts it is stored at revision 1 as the manifest the http +// source runs, and no answer shows its base URL or its tools. +func (s *ConnectorsSuite) TestACustomHTTPConnectorIsStoredAndItsAPIIsNeverShown() { + id := s.customID() + + created := s.create(s.httpConnector(id)) + + s.Equal(id, created.ID) + s.Equal(1, created.Revision) + s.True(created.Custom) + s.Equal([]string{none.Name}, created.Schemes) + s.Equal(created, s.get(id), "the answer to the create is the stored row") + stored, err := s.store.ConnectorDefinitions.Latest(context.Background(), s.customerID(), id) + s.Require().NoError(err) + s.Equal(map[string]string{core.SourceKindHTTP: "https://8.8.8.8"}, stored.Manifest.Endpoints) + s.Equal([]core.SourceRule{{Kind: core.SourceKindHTTP, Endpoint: core.SourceKindHTTP, HTTPTools: []core.HTTPTool{{ + Name: "get_forecast", Description: "The weather at a place.", Method: http.MethodGet, Path: "/v1/forecast", ReadOnly: true, + Parameters: map[string]core.HTTPParameter{ + "latitude": {Type: "number", Description: "Degrees north.", Required: true}, + "longitude": {Type: "number", Description: "Degrees east.", Required: true}, + "current": {Type: "string"}, + }}}}}, stored.Manifest.Sources) + for _, path := range []string{"/v1/agents/connectors/" + id, "/v1/agents/connectors?limit=200"} { + status, raw := s.serverClient.call(http.MethodGet, path, nil) + s.Require().Equal(http.StatusOK, status) + s.Contains(string(raw), id, path) + for _, hidden := range []string{"8.8.8.8", "base_url", `"http"`, "/v1/forecast", "get_forecast"} { + s.NotContains(string(raw), hidden, path) + } + } +} + +// TestAConnectionToAnHTTPConnectorListsItsReadOnlyTool is AC-2 of AI-3669 through the API: a +// connection with scheme none validates as connected, and its tools listing says the GET +// tool only reads. Discover sends nothing (internal/connectors/sources/http), so the API at +// the public address is never called. +func (s *ConnectorsSuite) TestAConnectionToAnHTTPConnectorListsItsReadOnlyTool() { + id := s.customID() + sent := s.httpConnector(id) + tools := sent["http"].(map[string]any)["tools"].([]map[string]any) + sent["http"].(map[string]any)["tools"] = append(tools, map[string]any{ + "name": "add_note", "description": "Adds a note.", "method": "POST", "path": "/v1/notes", + "parameters": map[string]any{"text": map[string]any{"type": "string", "required": true}}}, + // A GET tool is read-only only when the file says so. + map[string]any{"name": "list_notes", "description": "Lists the notes.", "method": "GET", "path": "/v1/notes"}) + s.create(sent) + var created Connection + s.Require().Equal(http.StatusCreated, s.serverClient.do(http.MethodPost, "/v1/agents/connections", appOwned(id), &created)) + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPut, "/v1/agents/connections/"+created.ID+"/credentials", + map[string]any{"expected_revision": 1}, nil)) + + var validation ConnectionValidation + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/connections/"+created.ID+"/validate", nil, &validation)) + var listed ConnectionTools + s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/connections/"+created.ID+"/tools", nil, &listed)) + + s.Equal(validationConnected, string(validation.Status), validation.Error) + readOnly := map[string]bool{} + for _, tool := range listed.Tools { + readOnly[tool.Name] = tool.ReadOnly + } + s.Equal(map[string]bool{"get_forecast": true, "add_note": false, "list_notes": false}, readOnly) +} + +// TestAReadOnlyToolThatWritesIsRefusedNamingIt is AC-5 of AI-3669 through the API: a POST or +// a DELETE tool saying read_only is a 400 naming the tool, and nothing is stored. +func (s *ConnectorsSuite) TestAReadOnlyToolThatWritesIsRefusedNamingIt() { + for _, method := range []string{http.MethodPost, http.MethodDelete} { + id := s.customID() + sent := s.httpConnector(id) + tool := sent["http"].(map[string]any)["tools"].([]map[string]any)[0] + tool["name"], tool["method"] = "remove_forecast", method + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, method) + s.Contains(failure, fmt.Sprintf(`a read-only tool must be GET or HEAD, and "remove_forecast" is %s`, method)) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), method) + } +} + +// TestAnHTTPConnectorWhoseAPIIsNotPublicHTTPSIsRefused is AC-7 of AI-3669 through the API, +// with AI-3674 S1.5's addresses and a few more: each is a 400 with one fixed message, so a +// caller cannot tell a name that does not resolve from a private one, and nothing is stored. +func (s *ConnectorsSuite) TestAnHTTPConnectorWhoseAPIIsNotPublicHTTPSIsRefused() { + for _, base := range []string{ + "https://127.0.0.1", // loopback + "https://10.0.0.1", // private-use, RFC 1918 + "https://169.254.169.254", // link-local, where cloud metadata servers answer + "http://api.open-meteo.com", // not https + "https://[::1]", // IPv6 loopback + "https://router-probe.invalid", // .invalid never resolves, RFC 6761 section 6.4 + "https://8.8.8.8/v1?key=secret", // a query + "https://user:secret@8.8.8.8", // userinfo + "https://8.8.8.8/v1#top", // a fragment + "HTTPS://8.8.8.8", // public to egress, which reads the scheme in any case, not to the manifest's rules + "https://8.8.8.8/{x}", // a {name} the manifest's rules refuse, since a custom connector declares no input + } { + id := s.customID() + sent := s.httpConnector(id) + sent["http"].(map[string]any)["base_url"] = base + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, base) + s.Equal("base_url must be a public https URL without userinfo, query or fragment", failure, base) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), base) + } +} + +// TestANewRevisionOfAnHTTPConnectorIsCheckedAgain: AI-3674 S1.5, the base URL is checked on +// every revision as on the first. A refused one leaves the stored revision as it was. +func (s *ConnectorsSuite) TestANewRevisionOfAnHTTPConnectorIsCheckedAgain() { + id := s.customID() + s.Equal(1, s.create(s.httpConnector(id)).Revision) + private := s.httpConnector(id) + private["http"].(map[string]any)["base_url"] = "https://169.254.169.254/v1" + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", private) + + s.Equal(http.StatusBadRequest, status) + s.Equal("base_url must be a public https URL without userinfo, query or fragment", failure) + stored, err := s.store.ConnectorDefinitions.Latest(context.Background(), s.customerID(), id) + s.Require().NoError(err) + s.Equal(1, stored.Revision) + s.Equal("https://8.8.8.8", stored.Manifest.Endpoints[core.SourceKindHTTP]) + moved := s.httpConnector(id) + moved["http"].(map[string]any)["base_url"] = "https://1.1.1.1" + s.Equal(2, s.create(moved).Revision) +} + +// TestAConnectorWithBothOrNeitherOfEndpointAndHTTPIsRefused: a custom connector is an MCP +// server or an http API, so one naming both or neither is refused and nothing is stored. +func (s *ConnectorsSuite) TestAConnectorWithBothOrNeitherOfEndpointAndHTTPIsRefused() { + both := s.httpConnector(s.customID()) + both["endpoint"] = "https://8.8.8.8/mcp" + neither := s.customConnector(s.customID()) + delete(neither, "endpoint") + empty := s.customConnector(s.customID()) + empty["endpoint"] = "" + for name, sent := range map[string]map[string]any{"both": both, "neither": neither, "an empty endpoint": empty} { + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, name) + s.Equal("a custom connector has an MCP endpoint or an http API, and exactly one of them", failure, name) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+sent["id"].(string), nil, nil), name) + } +} + +// TestAnHTTPConnectorTheManifestRefusesIsRefusedWithItsReason: an http block the schema takes +// but the manifest's rules refuse is a 400 with core's reason, and nothing is stored. +func (s *ConnectorsSuite) TestAnHTTPConnectorTheManifestRefusesIsRefusedWithItsReason() { + for name, test := range map[string]struct { + change func(sent, api map[string]any) + reason string + }{ + "oauth2_code": {func(sent, _ map[string]any) { + sent["schemes"], sent["client"] = []string{"oauth2_code"}, map[string]any{"registration": []string{"dcr"}} + }, "oauth2_code is not available for an http custom connector"}, + "a method override parameter": {func(_, api map[string]any) { + api["tools"].([]map[string]any)[0]["parameters"].(map[string]any)["_method"] = map[string]any{"type": "string"} + }, "parameters._method: names a method override"}, + } { + id := s.customID() + sent := s.httpConnector(id) + test.change(sent, sent["http"].(map[string]any)) + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, name) + s.Contains(failure, test.reason, name) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), name) + } +} + +// TestAnHTTPToolTheSchemaRefusesIsAValidationFailure: what the request's schema says of an +// http block (CustomHTTPAPI) is held before any rule of the manifest, an unknown field included. +func (s *ConnectorsSuite) TestAnHTTPToolTheSchemaRefusesIsAValidationFailure() { + for name, change := range map[string]func(api, tool, parameter map[string]any){ + "a method that is not one of the six": func(_, tool, _ map[string]any) { tool["method"] = "TRACE" }, + "a lowercase method": func(_, tool, _ map[string]any) { tool["method"] = "get" }, + "a parameter type that is no scalar": func(_, _, parameter map[string]any) { parameter["type"] = "object" }, + "a base_url over 2048": func(api, _, _ map[string]any) { api["base_url"] = "https://8.8.8.8/" + strings.Repeat("a", 2033) }, + "a header on a tool": func(_, tool, _ map[string]any) { + tool["headers"] = map[string]string{"X-HTTP-Method-Override": "DELETE"} + }, + "an unknown field of the api": func(api, _, _ map[string]any) { api["headers"] = map[string]string{"X-HTTP-Method-Override": "DELETE"} }, + "an unknown field of a parameter": func(_, _, parameter map[string]any) { parameter["in"] = "header" }, + "no base_url": func(api, _, _ map[string]any) { delete(api, "base_url") }, + "tools null": func(api, _, _ map[string]any) { api["tools"] = nil }, + "a parameter with no type": func(_, _, parameter map[string]any) { delete(parameter, "type") }, + // AI-3676 R1.4: core's caps and tool name pattern, which the schema carries. + "no tool": func(api, _, _ map[string]any) { api["tools"] = []any{} }, + "129 tools": func(api, tool, _ map[string]any) { + tools := make([]map[string]any, 129) + for i := range tools { + tools[i] = maps.Clone(tool) + tools[i]["name"] = fmt.Sprintf("tool_%d", i) + } + api["tools"] = tools + }, + "a name of 64": func(_, tool, _ map[string]any) { tool["name"] = strings.Repeat("n", 64) }, + "a name with a dot": func(_, tool, _ map[string]any) { tool["name"] = "get.forecast" }, + "a description over 1000": func(_, tool, _ map[string]any) { tool["description"] = strings.Repeat("d", 1001) }, + "a path over 2048": func(_, tool, _ map[string]any) { tool["path"] = "/" + strings.Repeat("p", 2048) }, + "a parameter description over 1000": func(_, _, parameter map[string]any) { parameter["description"] = strings.Repeat("d", 1001) }, + "65 parameters": func(_, tool, _ map[string]any) { + parameters := tool["parameters"].(map[string]any) + for i := len(parameters); i < 65; i++ { + parameters[fmt.Sprintf("p%d", i)] = map[string]any{"type": "string"} + } + }, + } { + id := s.customID() + sent := s.httpConnector(id) + api := sent["http"].(map[string]any) + tool := api["tools"].([]map[string]any)[0] + change(api, tool, tool["parameters"].(map[string]any)["latitude"].(map[string]any)) + + status, raw := s.serverClient.call(http.MethodPost, "/v1/agents/connectors", sent) + + s.Equal(http.StatusBadRequest, status, name) + var answered ErrorResponse + s.Require().NoError(json.Unmarshal(raw, &answered), name) + s.Equal("validation_failed", answered.Error.Code, "%s: %s", name, raw) + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+id, nil, nil), name) + } +} + +// httpConnector is AC-1 of AI-3669's open_meteo as the CLI posts it, scheme none, at a public +// IP literal, so checking it resolves nothing. +func (s *ConnectorsSuite) httpConnector(id string) map[string]any { + return map[string]any{ + "id": id, + "name": "Open-Meteo", + "schemes": []string{none.Name}, + "http": map[string]any{ + "base_url": "https://8.8.8.8", + "tools": []map[string]any{{ + "name": "get_forecast", "description": "The weather at a place.", "method": "GET", "path": "/v1/forecast", + "read_only": true, + "parameters": map[string]any{ + "latitude": map[string]any{"type": "number", "description": "Degrees north.", "required": true}, + "longitude": map[string]any{"type": "number", "description": "Degrees east.", "required": true}, + "current": map[string]any{"type": "string"}, + }, + }}, + }, + } +} + // customConnector is a custom MCP connector the router accepts. Its endpoint is a public IP // literal, so checking it resolves nothing. func (s *ConnectorsSuite) customConnector(id string) map[string]any { diff --git a/acceleration/internal/api/datamove_test.go b/acceleration/internal/api/datamove_test.go index f2801e2d6a..7ceb0ca092 100644 --- a/acceleration/internal/api/datamove_test.go +++ b/acceleration/internal/api/datamove_test.go @@ -224,6 +224,28 @@ func (s *DataMoveSuite) TestAnImportedConnectorNamingTheOperatorsClientAfterAnot s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+refused, nil, nil)) } +// TestAnImportedHTTPConnectorIsCheckedAsTheAPIChecksIt: POST /v1/data/import takes an http +// connector the API would create (AI-3676), and refuses one whose API is on a private address +// with the create's own message, storing nothing. +func (s *DataMoveSuite) TestAnImportedHTTPConnectorIsCheckedAsTheAPIChecksIt() { + refused, taken := "custom_"+store.NewID(), "custom_"+store.NewID() + line := func(id, base string) dataLine { + return dataLine{Table: "connector_definitions", Row: json.RawMessage(`{"id": "` + id + `", "revision": 1, "name": "Acme", + "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": {"id": "` + id + `", "revision": 1, + "name": "Acme", "schemes": ["api_key"], "endpoints": {"http": "` + base + `"}, "sources": [{"kind": "http", "endpoint": "http", + "http_tools": [{"name": "get_item", "description": "Reads an item.", "method": "GET", "path": "/items", "read_only": true}]}]}}`)} + } + + status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import?full=true", ndjson([]dataLine{line(refused, "https://10.0.0.1")})) + taking := s.serverClient.do(http.MethodPost, "/v1/data/import?full=true", ndjson([]dataLine{line(taken, "https://8.8.8.8")}), nil) + + s.Equal(http.StatusBadRequest, status) + s.Contains(failure, "base_url must be a public https URL without userinfo, query or fragment") + s.Equal(http.StatusNotFound, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+refused, nil, nil)) + s.Equal(http.StatusOK, taking) + s.Equal(http.StatusOK, s.serverClient.do(http.MethodGet, "/v1/agents/connectors/"+taken, nil, nil)) +} + // A database that fails is the router's failure, and its text names the database's address. func (s *DataMoveSuite) TestAnImportTheDatabaseCannotWriteIsAFailureWithNoDatabaseText() { id := "custom_" + store.NewID() diff --git a/acceleration/internal/connectors/core/custom.go b/acceleration/internal/connectors/core/custom.go index c654c0b3ce..f0d9bab008 100644 --- a/acceleration/internal/connectors/core/custom.go +++ b/acceleration/internal/connectors/core/custom.go @@ -1,11 +1,13 @@ package core import ( + "context" "encoding/json" "errors" "slices" "strings" + "github.com/GetStream/Vision-Agents/acceleration/internal/egress" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) @@ -28,6 +30,24 @@ type CustomConnector struct { Client ClientPolicy } +// CheckBaseURL is nil for a base URL an http custom connector may have, and one answer for every +// other: a caller who creates or imports one (customManifest in internal/api/connectors.go, +// importableDefinition in internal/store/datamove.go) checks it before CustomManifest, whose +// rules would answer some of them in their own words (AC-7 of AI-3669). One answer, since +// egress's own errors tell a name that does not resolve from one that resolves to a private +// address, which would let a caller probe the names the router's resolver knows. It resolves +// the host, last, after the checks that cost nothing. +func CheckBaseURL(ctx context.Context, baseURL string) error { + // The endpoint rules Manifest.Validate holds an http custom connector's base URL to: its + // cap, and checkTemplate's for a manifest that declares no input, capture or var, where a + // URL starts with https:// and a {name} names nothing. + if len(baseURL) > maxHTTPPath || !strings.HasPrefix(baseURL, "https://") || strings.ContainsAny(baseURL, "{}") || + egress.ValidatePublicHTTPSURL(ctx, baseURL) != nil { + return stack.Wrap(errors.New("base_url must be a public https URL without userinfo, query or fragment")) + } + return nil +} + // CustomManifest is the manifest a custom connector is stored as, or why it cannot be: one MCP // source at Endpoint, or one http source at BaseURL with Tools, and of the client only its // registration, auth_method and alg. Which schemes the deployment has and whether Endpoint or diff --git a/acceleration/internal/connectors/core/http_tools.go b/acceleration/internal/connectors/core/http_tools.go index 103ace24c0..87e7fb3a2d 100644 --- a/acceleration/internal/connectors/core/http_tools.go +++ b/acceleration/internal/connectors/core/http_tools.go @@ -57,10 +57,12 @@ const ( // OpenAI documents taking in one request. maxHTTPTools = 128 // maxHTTPToolDescription is the cap a custom connector's own description has - // (CustomConnectorRequest.Description, internal/api/connectors.go). + // (CustomConnectorRequest.Description, internal/api/connectors.go), on a tool's description + // and on each of its parameters'. maxHTTPToolDescription = 1000 // maxHTTPPath is the cap a custom connector's MCP endpoint URL has - // (CustomConnectorRequest.Endpoint, internal/api/connectors.go). + // (CustomConnectorRequest.Endpoint, internal/api/connectors.go), on a tool's path and on the + // http source's endpoint, its base URL. maxHTTPPath = 2048 // maxHTTPParameters is the cap an agent config has on its connector bindings and its // visible_tools (internal/api/configs.go). @@ -177,6 +179,9 @@ func checkHTTPSource(fail func(field, format string, args ...any), field string, if !slices.Contains(httpParameterTypes, tool.Parameters[name].Type) { fail(field+".type", "%q is not one of %v", tool.Parameters[name].Type, httpParameterTypes) } + if len(tool.Parameters[name].Description) > maxHTTPToolDescription { + fail(field+".description", "is over %d bytes", maxHTTPToolDescription) + } } } } diff --git a/acceleration/internal/connectors/core/http_tools_test.go b/acceleration/internal/connectors/core/http_tools_test.go index 7007ff7335..93a7755dad 100644 --- a/acceleration/internal/connectors/core/http_tools_test.go +++ b/acceleration/internal/connectors/core/http_tools_test.go @@ -90,6 +90,11 @@ func (s *HTTPSourceSuite) TestAValidHTTPSourceIsAccepted() { "a parameter merely holding method": withTool(func(t *HTTPTool) { t.Parameters["http_method_name"] = HTTPParameter{Type: "string"} }), "a header that is no override": withSource(func(r *SourceRule) { r.Headers = map[string]string{"X-Api-Version": "2"} }), "outbound true": withSource(func(r *SourceRule) { r.Outbound = new(true) }), + "a base_url of 2048 bytes": func() Manifest { + m := httpManifest(forecast()) + m.Endpoints[SourceKindHTTP] = "https://api.example.com/" + strings.Repeat("a", 2024) + return m + }(), "an mcp source with an override header": {ID: "example", Revision: 1, Name: "Example", Schemes: []string{"bearer"}, Endpoints: map[string]string{SourceKindMCP: "https://api.example.com/mcp"}, Sources: []SourceRule{{Kind: SourceKindMCP, Endpoint: SourceKindMCP, Headers: map[string]string{"X-HTTP-Method-Override": "POST"}}}}, @@ -149,7 +154,20 @@ func (s *HTTPSourceSuite) TestAnHTTPSourceBreakingARuleIsRefused() { "a brace": {withTool(func(t *HTTPTool) { t.Parameters["a}b"] = HTTPParameter{Type: "string"} }), `"a}b" is not 1 to 64`}, "an empty name": {withTool(func(t *HTTPTool) { t.Parameters[""] = HTTPParameter{Type: "string"} }), `"" is not 1 to 64`}, "a name of 65": {withTool(func(t *HTTPTool) { t.Parameters[strings.Repeat("p", 65)] = HTTPParameter{Type: "string"} }), `is not 1 to 64`}, - "65 parameters": {withTool(func(t *HTTPTool) { t.Parameters = parameters(65) }), `http_tools[0].parameters: has 65 parameters, over 64`}, + "a parameter description over 1000": {withTool(func(t *HTTPTool) { + t.Parameters["days"] = HTTPParameter{Type: "integer", Description: strings.Repeat("d", 1001)} + }), `http_tools[0].parameters.days.description: is over 1000 bytes`}, + "a base_url of 2049": {func() Manifest { + m := httpManifest(forecast()) + m.Endpoints[SourceKindHTTP] = "https://api.example.com/" + strings.Repeat("a", 2025) + return m + }(), `endpoints.http: is over 2048 bytes`}, + "a base_url over 2048": {func() Manifest { + m := httpManifest(forecast()) + m.Endpoints[SourceKindHTTP] = "https://api.example.com/" + strings.Repeat("a", 2048) + return m + }(), `endpoints.http: is over 2048 bytes`}, + "65 parameters": {withTool(func(t *HTTPTool) { t.Parameters = parameters(65) }), `http_tools[0].parameters: has 65 parameters, over 64`}, "an override header": {withSource(func(r *SourceRule) { r.Headers = map[string]string{"x-HTTP-method-OVERRIDE": "POST"} }), `sources[0].headers.x-HTTP-method-OVERRIDE: names a method override`}, "read_only_tools": {withSource(func(r *SourceRule) { r.ReadOnlyTools = []string{"get_forecast"} }), `sources[0].read_only_tools: is not set on an http source`}, diff --git a/acceleration/internal/connectors/core/manifest.go b/acceleration/internal/connectors/core/manifest.go index cc5b0ab84e..503faae7fc 100644 --- a/acceleration/internal/connectors/core/manifest.go +++ b/acceleration/internal/connectors/core/manifest.go @@ -832,6 +832,10 @@ func (m Manifest) Validate() error { fail(field+".kind", "is http a second time: a manifest has at most one http source") } checkHTTPSource(fail, field, source) + // An import has no request schema to cap it (maxLength on CustomHTTPAPI.base_url). + if endpoint := m.Endpoints[source.Endpoint]; len(endpoint) > maxHTTPPath { + fail("endpoints."+source.Endpoint, "is over %d bytes", maxHTTPPath) + } } else if len(source.HTTPTools) > 0 { fail(field+".http_tools", "is set only on a source of kind %s", SourceKindHTTP) } diff --git a/acceleration/internal/connectors/sources/http/AGENTS.md b/acceleration/internal/connectors/sources/http/AGENTS.md index 59aaf29eb1..a0b35bc1a7 100644 --- a/acceleration/internal/connectors/sources/http/AGENTS.md +++ b/acceleration/internal/connectors/sources/http/AGENTS.md @@ -1,6 +1,6 @@ # internal/connectors/sources/http -The `core.ToolSource` for a connector whose manifest lists its own tools, registered as `http` (`Kind`, `core.SourceKindHTTP`), the name a manifest's `sources[].kind` gives it. Each tool in `sources[].http_tools` (`core.HTTPTool`, validated in `core/http_tools.go`) is one HTTP request to the source's endpoint. Callers, through `core.Registry.ToolSources` (`cmd/router/main.go`): `POST /v1/agents/connections/{id}/validate` (`Discover`, `internal/api/connection_tools.go`) and the session (`Open`, `internal/session/connector_tools.go`), whose dispatcher runs `Toolset.Call` and bounds it itself. No stored connector has kind `http` until the API takes one (AI-3676): an import refuses one too (`importableDefinition`, `internal/store/datamove.go`) until then. +The `core.ToolSource` for a connector whose manifest lists its own tools, registered as `http` (`Kind`, `core.SourceKindHTTP`), the name a manifest's `sources[].kind` gives it. Each tool in `sources[].http_tools` (`core.HTTPTool`, validated in `core/http_tools.go`) is one HTTP request to the source's endpoint. Callers, through `core.Registry.ToolSources` (`cmd/router/main.go`): `POST /v1/agents/connections/{id}/validate` (`Discover`, `internal/api/connection_tools.go`) and the session (`Open`, `internal/session/connector_tools.go`), whose dispatcher runs `Toolset.Call` and bounds it itself. A connector of kind `http` is stored by `POST /v1/agents/connectors` with an `http` block (`customManifest`, `internal/api/connectors.go`) or by an import (`importableDefinition`, `internal/store/datamove.go`), each only with a public https base URL (`egress.ValidatePublicHTTPSURL`). ## Flow diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index 3ecd8cb0ed..513efe4bf7 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -779,6 +779,10 @@ func (t dataTable) selectRows(customerID string, secrets []string) (string, []an // is what lets a move be resumed after it was interrupted. func (s *Store) ImportRow(ctx context.Context, customerID, table string, row json.RawMessage) error { spec, _ := dataTableByName(table) + row, err := importableRow(ctx, customerID, table, row) + if err != nil { + return err + } var stale []string if err := s.importRow(ctx, s.sideOf(spec), customerID, table, row, &stale); err != nil { return err @@ -801,8 +805,26 @@ func (s *Store) sideOf(table dataTable) *bun.DB { var lineColumns = []string{"stream_trunk_id", "stream_route_id", "stream_app_pk", "stream_call_id", "stream_call_type", "attached_at", "config_id"} -// importRow writes one row of an export or of a change (ImportRow). It adds to stale the cached -// values the row was and is read through, for the caller to forget once the write has committed. +// importableRow is row as importRow writes it, or why it is not imported: a connector definition +// only as the API would store it (importableDefinition). Every caller runs it before importRow and +// outside any transaction, since checking a definition can resolve its base URL's host, and a slow +// resolver would hold applyChanges' transaction open as long as the request lasts. +func importableRow(ctx context.Context, customerID, table string, row json.RawMessage) (json.RawMessage, error) { + if table != "connector_definitions" { + return row, nil + } + // The built-in customer owns the built-in definitions every app shares, and an import + // never writes them: `router replicate` without --as hands over "" until a row names + // a customer. + if customerID == BuiltinCustomer { + return nil, fmt.Errorf("store: an import writes a connector definition under a customer, and none is known yet: %w (name the customer with --as)", ErrNotACustomConnector) + } + return importableDefinition(ctx, row) +} + +// importRow writes one row of an export or of a change (ImportRow), which importableRow has +// checked. It adds to stale the cached values the row was and is read through, for the caller to +// forget once the write has committed. func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table string, row json.RawMessage, stale *[]string) error { if slices.Contains(retiredTables, table) { return nil @@ -838,17 +860,6 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str return err } } - if table == "connector_definitions" { - // The built-in customer owns the built-in definitions every app shares, and an import - // never writes them: `router replicate` without --as hands over "" until a row names - // a customer. - if customerID == BuiltinCustomer { - return fmt.Errorf("store: an import writes a connector definition under a customer, and none is known yet: %w (name the customer with --as)", ErrNotACustomConnector) - } - if row, err = importableDefinition(row); err != nil { - return err - } - } shape, err := s.shapeOf(ctx, table) if err != nil { return err @@ -1650,8 +1661,9 @@ func boughtHere(relation string) string { // the API would have stored it, so no field this release does not read arrives for one that does. Every imported // definition is a custom one, since the customer is forced onto the row (identity) and importRow refuses an import with // no customer, and only the API's rules keep a custom manifest from naming the operator's client or anything else the -// router would trust a built-in with (core.Manifest.AsCustom). -func importableDefinition(row json.RawMessage) (json.RawMessage, error) { +// router would trust a built-in with (core.Manifest.AsCustom). An http one's base URL is checked as the API checks it +// (core.CheckBaseURL). +func importableDefinition(ctx context.Context, row json.RawMessage) (json.RawMessage, error) { // Read by exact column name, as the insert reads the row: a JSON decoder also matches a // key in another case, which the insert then leaves out. var fields map[string]json.RawMessage @@ -1670,16 +1682,17 @@ func importableDefinition(row json.RawMessage) (json.RawMessage, error) { return nil, invalidImport(fmt.Errorf("store: read the manifest of imported connector definition %q: %w", id, err)) } } + // Before AsCustom, whose rules would answer an http:// one in their own words: one answer for every base URL + // refused, as the API answers (an app imports its own export). + if core.HTTPSource(manifest.Sources) != nil { + if err := core.CheckBaseURL(ctx, manifest.Endpoints[core.SourceKindHTTP]); err != nil { + return nil, fmt.Errorf("store: imported connector definition %q: %w: %w", id, ErrNotACustomConnector, err) + } + } custom, err := manifest.AsCustom(id) if err != nil { return nil, fmt.Errorf("store: imported connector definition %q: %w: %w", id, ErrNotACustomConnector, err) } - // The http source runs a stored tool before the call-time checks of AI-3675 exist, and the - // API stores no http connector before AI-3676, so no import stores one either, even one the - // rules above let through. AI-3676 lifts this. - if core.HTTPSource(custom.Sources) != nil { - return nil, fmt.Errorf("store: imported connector definition %q: %w: an http connector cannot be imported yet", id, ErrNotACustomConnector) - } if fields["manifest"], err = json.Marshal(custom); err != nil { return nil, stack.Wrap(err) } @@ -1942,6 +1955,18 @@ func (s *Store) applyChanges(ctx context.Context, db *bun.DB, customerID string, if len(changes) == 0 { return nil } + // Before the transaction opens (importableRow). + changes = slices.Clone(changes) + for i, change := range changes { + if change.Op == ChangeDelete || !appPolicy(change) { + continue + } + payload, err := importableRow(ctx, customerID, change.Table, change.Payload) + if err != nil { + return err + } + changes[i].Payload = payload + } var stale []string err := db.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { for _, change := range changes { diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 9016acbcf6..60744f0306 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -2417,21 +2417,74 @@ func (s *DataMoveSuite) TestAnImportedDefinitionWhoseServerIsNotHTTPSIsRefused() } // customWeather is a manifest the API stores for a custom http connector custom_weather: one -// read-only GET tool on an API taking a key. -const customWeather = `{"id": "custom_acme", "revision": 1, "name": "Weather", "endpoints": {"http": "https://api.weather.example/v1"}, +// read-only GET tool on an API taking a key, at a public IP literal, so checking it resolves nothing. +const customWeather = `{"id": "custom_acme", "revision": 1, "name": "Weather", "endpoints": {"http": "https://8.8.8.8/v1"}, "schemes": ["api_key"], "sources": [{"kind": "http", "endpoint": "http", "http_tools": [{"name": "get_forecast", "description": "The forecast for a city.", "method": "GET", "path": "/forecast/{city}", "read_only": true, "parameters": {"city": {"type": "string", "required": true}}}]}]}` -// TestAnImportedHTTPDefinitionIsRefused: a definition the API would store for an http connector -// is refused, and writes nothing, until AI-3676 lifts it (importableDefinition). -func (s *DataMoveSuite) TestAnImportedHTTPDefinitionIsRefused() { +// TestAnImportedHTTPDefinitionIsStored: a definition the API would store for an http connector +// is stored as the API stores it (AI-3676 lifts AI-3674's refusal). +func (s *DataMoveSuite) TestAnImportedHTTPDefinitionIsStored() { id, err := s.importDefinition(customWeather) + s.Require().NoError(err) + s.Equal(1, s.definitionsNamed(id)) + var stored string + s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, + "SELECT manifest FROM connector_definitions WHERE customer_id = 'moved' AND id = ?", id).Scan(&stored)) + s.JSONEq(strings.Replace(customWeather, `"id": "custom_acme"`, `"id": "`+id+`"`, 1), stored) +} + +// TestAnImportedHTTPDefinitionWhoseAPIIsPrivateIsRefused: an import checks the base URL as the +// API does (AI-3674 S1.5), and writes nothing. +func (s *DataMoveSuite) TestAnImportedHTTPDefinitionWhoseAPIIsPrivateIsRefused() { + id, err := s.importDefinition(strings.Replace(customWeather, "https://8.8.8.8/v1", "https://169.254.169.254/v1", 1)) + s.ErrorIs(err, ErrNotACustomConnector) - s.ErrorContains(err, "an http connector cannot be imported yet") + s.ErrorContains(err, "base_url must be a public https URL without userinfo, query or fragment") s.Zero(s.definitionsNamed(id)) } +// TestAChangesDefinitionsAreCheckedBeforeItsTransactionOpens: AI-3676 S1.3, checking a +// definition can resolve its base URL's host, so a change set's definitions are checked before +// its transaction opens, not row by row inside it. The first change names no table and fails +// only once inside the transaction; the definition after it is refused first. +func (s *DataMoveSuite) TestAChangesDefinitionsAreCheckedBeforeItsTransactionOpens() { + id := "custom_" + newID() + private := strings.Replace(strings.Replace(customWeather, "https://8.8.8.8/v1", "https://169.254.169.254/v1", 1), + `"id": "custom_acme"`, `"id": "`+id+`"`, 1) + + err := s.destination.ApplyChanges(s.ctx, "moved", []DataChange{ + {Table: "no_such_table", Op: ChangeInsert, Payload: json.RawMessage(`{}`)}, + {Table: "connector_definitions", Op: ChangeInsert, Payload: json.RawMessage(`{"id": "` + id + `", "revision": 1, + "name": "Weather", "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": ` + private + `}`)}, + }) + + s.ErrorIs(err, ErrNotACustomConnector) + s.ErrorContains(err, "base_url must be a public https URL without userinfo, query or fragment") + s.NotErrorIs(err, ErrInvalidImport) + s.Zero(s.definitionsNamed(id)) +} + +// TestAChangesDefinitionArrivesWithoutAFieldThisReleaseDoesNotRead: a change set's definition is +// stored as the API would store it, as an import's is: the check before the transaction hands +// its normalized row on (applyChanges). +func (s *DataMoveSuite) TestAChangesDefinitionArrivesWithoutAFieldThisReleaseDoesNotRead() { + id := "custom_" + newID() + manifest := strings.Replace(customManifestWith(`"later": {"env": "GOOGLE"}`), "custom_acme", id, 1) + + err := s.destination.ApplyChanges(s.ctx, "moved", []DataChange{{Table: "connector_definitions", Op: ChangeInsert, + Payload: json.RawMessage(`{"id": "` + id + `", "revision": 1, "name": "Acme", "category": "", "description": "", "created_at": "2026-11-01T00:00:00Z", "manifest": ` + manifest + `}`)}}) + + s.Require().NoError(err) + var stored string + s.Require().NoError(s.destination.GlobalDB().QueryRowContext(s.ctx, + "SELECT manifest FROM connector_definitions WHERE customer_id = 'moved' AND id = ?", id).Scan(&stored)) + var manifestStored map[string]any + s.Require().NoError(json.Unmarshal([]byte(stored), &manifestStored)) + s.NotContains(manifestStored, "later") +} + // TestAnImportedHTTPDefinitionWhoseReadOnlyToolWritesIsRefused: the http tool rules // (core.Manifest.Validate) hold for an import as for the API. func (s *DataMoveSuite) TestAnImportedHTTPDefinitionWhoseReadOnlyToolWritesIsRefused() { diff --git a/acceleration/internal/store/datamove_unit_test.go b/acceleration/internal/store/datamove_unit_test.go index 2f7c9c610e..95b3d2822f 100644 --- a/acceleration/internal/store/datamove_unit_test.go +++ b/acceleration/internal/store/datamove_unit_test.go @@ -1,7 +1,9 @@ package store import ( + "context" "encoding/json" + "strings" "testing" "github.com/stretchr/testify/suite" @@ -17,25 +19,58 @@ func TestImportableDefinitionSuite(t *testing.T) { suite.Run(t, new(ImportableDefinitionSuite)) } -// AI-3674 R1.1: the http source would run an imported http connector's tools before AI-3675's -// call-time checks, so an import refuses one until AI-3676 lifts it. An MCP one is still stored. -func (s *ImportableDefinitionSuite) TestAnHTTPConnectorIsRefusedAndAnMCPOneKept() { - http := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"http": "https://api.crm.example"}, - "schemes": ["bearer"], "sources": [{"kind": "http", "endpoint": "http", - "http_tools": [{"name": "delete_item", "description": "Deletes an item.", "method": "DELETE", "path": "/items/{id}", - "parameters": {"id": {"type": "string", "required": true}}}]}]}` +// importedHTTP is a manifest the API stores for an http connector whose API is at a public IP literal, so checking it +// resolves nothing. +const importedHTTP = `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"http": "https://8.8.8.8/api"}, + "schemes": ["bearer"], "sources": [{"kind": "http", "endpoint": "http", + "http_tools": [{"name": "delete_item", "description": "Deletes an item.", "method": "DELETE", "path": "/items/{id}", + "parameters": {"id": {"type": "string", "required": true}}}]}]}` + +// AI-3676 lifts AI-3674's refusal: an http connector is imported as the API stores one, and an MCP one as before. +func (s *ImportableDefinitionSuite) TestAnHTTPConnectorAndAnMCPOneAreKept() { mcp := `{"id": "custom_crm", "revision": 1, "name": "CRM", "endpoints": {"mcp": "https://mcp.crm.example/mcp"}, "schemes": ["bearer"], "sources": [{"kind": "mcp", "endpoint": "mcp"}]}` + // 2048 bytes, the cap itself: pins the cap as maxHTTPPath, not one under it. + atTheCap := strings.Replace(importedHTTP, "https://8.8.8.8/api", "https://8.8.8.8/"+strings.Repeat("a", 2032), 1) + for _, manifest := range []string{importedHTTP, mcp, atTheCap} { + row, err := importableDefinition(context.Background(), json.RawMessage(`{"id": "custom_crm", "manifest": `+manifest+`}`)) + + s.Require().NoError(err) + var kept map[string]json.RawMessage + s.Require().NoError(json.Unmarshal(row, &kept)) + s.JSONEq(manifest, string(kept["manifest"])) + } +} - _, err := importableDefinition(json.RawMessage(`{"id": "custom_crm", "manifest": ` + http + `}`)) +// AI-3674 S1.5: an import checks an http connector's base URL as the API does, with AC-7 of AI-3669's addresses, and +// answers each the same, so an import cannot tell a private address from one that does not resolve. +func (s *ImportableDefinitionSuite) TestAnHTTPConnectorWhoseAPIIsNotPublicIsRefused() { + for _, base := range []string{"https://127.0.0.1", "https://10.0.0.1", "https://169.254.169.254", "https://[::1]", + "https://router-probe.invalid", + // S1.2: refused by core's rules too, which would answer each in their own words. + "http://8.8.8.8/api", "HTTPS://8.8.8.8/api", "https://8.8.8.8/{x}", "https://8.8.8.8/" + strings.Repeat("a", 2048), + // 2049 bytes, one over the cap: pins the cap as maxHTTPPath, not maxHTTPPath+1. + "https://8.8.8.8/" + strings.Repeat("a", 2033)} { + manifest := strings.Replace(importedHTTP, "https://8.8.8.8/api", base, 1) - s.ErrorIs(err, ErrNotACustomConnector) - s.ErrorContains(err, "an http connector cannot be imported yet") + _, err := importableDefinition(context.Background(), json.RawMessage(`{"id": "custom_crm", "manifest": `+manifest+`}`)) + + s.ErrorIs(err, ErrNotACustomConnector, base) + s.EqualError(err, `store: imported connector definition "custom_crm": `+ErrNotACustomConnector.Error()+ + ": base_url must be a public https URL without userinfo, query or fragment", base) + } +} - row, err := importableDefinition(json.RawMessage(`{"id": "custom_crm", "manifest": ` + mcp + `}`)) +// AI-3676 S1.1: an import has no request body limit to keep an http connector small, so core's caps refuse what the +// API's schema would: a parameter's description over 1000 bytes and a base URL over 2048. +func (s *ImportableDefinitionSuite) TestAnOversizedHTTPConnectorIsRefused() { + for name, manifest := range map[string]string{ + "a 2 MiB parameter description": strings.Replace(importedHTTP, `"parameters": {"id": {"type": "string", "required": true}}`, + `"parameters": {"id": {"type": "string", "required": true}, "q": {"type": "string", "description": "`+strings.Repeat("x", 2<<20)+`"}}`, 1), + "a 4 KiB base_url": strings.Replace(importedHTTP, "https://8.8.8.8/api", "https://8.8.8.8/"+strings.Repeat("a", 4096), 1), + } { + _, err := importableDefinition(context.Background(), json.RawMessage(`{"id": "custom_crm", "manifest": `+manifest+`}`)) - s.Require().NoError(err) - var kept map[string]json.RawMessage - s.Require().NoError(json.Unmarshal(row, &kept)) - s.JSONEq(mcp, string(kept["manifest"])) + s.ErrorIs(err, ErrNotACustomConnector, name) + } } diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py index 5ff8328d83..5c24360be0 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/create_connector.py @@ -90,17 +90,17 @@ def sync_detailed( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Response[Connector | ErrorResponse]: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -126,17 +126,17 @@ def sync( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Connector | ErrorResponse | None: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -157,17 +157,17 @@ async def asyncio_detailed( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Response[Connector | ErrorResponse]: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -191,17 +191,17 @@ async def asyncio( client: AuthenticatedClient | Client, body: CustomConnectorRequest, ) -> Connector | ErrorResponse | None: - """Add a custom MCP connector + """Add a custom connector - Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores - its next revision, which connections pick up when they reconnect; sending the same definition again - changes nothing. A built-in cannot be changed this way. + Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an + id the app already has stores its next revision, which connections pick up when they reconnect; + sending the same definition again changes nothing. A built-in cannot be changed this way. Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. Args: - body (CustomConnectorRequest): A custom MCP server for the app's agents to connect to. An - unknown field is refused rather than ignored. + body (CustomConnectorRequest): A custom MCP server or HTTP API for the app's agents to + connect to. An unknown field is refused rather than ignored. Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py index eb282be23d..ebaafbca39 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/__init__.py @@ -241,6 +241,12 @@ from .credit_entry_kind import CreditEntryKind from .credit_page import CreditPage from .custom_connector_request import CustomConnectorRequest +from .custom_http_parameter import CustomHTTPParameter +from .custom_http_parameter_type import CustomHTTPParameterType +from .custom_http_tool import CustomHTTPTool +from .custom_http_tool_method import CustomHTTPToolMethod +from .custom_http_tool_parameters import CustomHTTPToolParameters +from .custom_httpapi import CustomHTTPAPI from .custom_model import CustomModel from .custom_model_page import CustomModelPage from .custom_model_request import CustomModelRequest @@ -913,6 +919,12 @@ "CreditEntryKind", "CreditPage", "CustomConnectorRequest", + "CustomHTTPAPI", + "CustomHTTPParameter", + "CustomHTTPParameterType", + "CustomHTTPTool", + "CustomHTTPToolMethod", + "CustomHTTPToolParameters", "CustomModel", "CustomModelPage", "CustomModelRequest", diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py index bf23e5b0a3..49fc4f711d 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_connector_request.py @@ -10,6 +10,7 @@ if TYPE_CHECKING: from ..models.connector_client import ConnectorClient + from ..models.custom_httpapi import CustomHTTPAPI T = TypeVar("T", bound="CustomConnectorRequest") @@ -17,36 +18,36 @@ @_attrs_define class CustomConnectorRequest: - """A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. + """A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. Attributes: - endpoint (str): The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An - address on a private network, loopback or link-local is refused. id (str): Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. name (str): schemes (list[str] | None): How a connection may authenticate. Each must be a scheme this deployment has, except oauth2_client_credentials, which a custom connector cannot use: it needs a token endpoint a custom connector cannot set. + endpoint (str | Unset): The MCP server, over Streamable HTTP: a public https URL without userinfo, query or + fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. category (str | Unset): client (ConnectorClient | Unset): How the OAuth client a connection uses is registered, and how the client authenticates at the token endpoint. description (str | Unset): scopes (list[str] | None | Unset): The scopes a consent asks for, each an RFC 6749 scope token. + http (CustomHTTPAPI | Unset): An HTTP API a custom connector calls, and the tools it offers an agent. """ - endpoint: str id: str name: str schemes: list[str] | None + endpoint: str | Unset = UNSET category: str | Unset = UNSET client: ConnectorClient | Unset = UNSET description: str | Unset = UNSET scopes: list[str] | None | Unset = UNSET + http: CustomHTTPAPI | Unset = UNSET def to_dict(self) -> dict[str, Any]: - endpoint = self.endpoint - id = self.id name = self.name @@ -58,6 +59,8 @@ def to_dict(self) -> dict[str, Any]: else: schemes = self.schemes + endpoint = self.endpoint + category = self.category client: dict[str, Any] | Unset = UNSET @@ -75,16 +78,21 @@ def to_dict(self) -> dict[str, Any]: else: scopes = self.scopes + http: dict[str, Any] | Unset = UNSET + if not isinstance(self.http, Unset): + http = self.http.to_dict() + field_dict: dict[str, Any] = {} field_dict.update( { - "endpoint": endpoint, "id": id, "name": name, "schemes": schemes, } ) + if endpoint is not UNSET: + field_dict["endpoint"] = endpoint if category is not UNSET: field_dict["category"] = category if client is not UNSET: @@ -93,16 +101,17 @@ def to_dict(self) -> dict[str, Any]: field_dict["description"] = description if scopes is not UNSET: field_dict["scopes"] = scopes + if http is not UNSET: + field_dict["http"] = http return field_dict @classmethod def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: from ..models.connector_client import ConnectorClient + from ..models.custom_httpapi import CustomHTTPAPI d = dict(src_dict) - endpoint = d.pop("endpoint") - id = d.pop("id") name = d.pop("name") @@ -122,6 +131,8 @@ def _parse_schemes(data: object) -> list[str] | None: schemes = _parse_schemes(d.pop("schemes")) + endpoint = d.pop("endpoint", UNSET) + category = d.pop("category", UNSET) _client = d.pop("client", UNSET) @@ -150,15 +161,23 @@ def _parse_scopes(data: object) -> list[str] | None | Unset: scopes = _parse_scopes(d.pop("scopes", UNSET)) + _http = d.pop("http", UNSET) + http: CustomHTTPAPI | Unset + if isinstance(_http, Unset): + http = UNSET + else: + http = CustomHTTPAPI.from_dict(_http) + custom_connector_request = cls( - endpoint=endpoint, id=id, name=name, schemes=schemes, + endpoint=endpoint, category=category, client=client, description=description, scopes=scopes, + http=http, ) return custom_connector_request diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter.py new file mode 100644 index 0000000000..6e252c2561 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, TypeVar + +from attrs import define as _attrs_define +from typing_extensions import Self + +from ..models.custom_http_parameter_type import CustomHTTPParameterType +from ..types import UNSET, Unset + +T = TypeVar("T", bound="CustomHTTPParameter") + + +@_attrs_define +class CustomHTTPParameter: + """One value the model gives an http tool. + + Attributes: + type_ (CustomHTTPParameterType): + description (str | Unset): + required (bool | Unset): The model must give it. A parameter in the path must be required. + """ + + type_: CustomHTTPParameterType + description: str | Unset = UNSET + required: bool | Unset = UNSET + + def to_dict(self) -> dict[str, Any]: + type_ = self.type_.value + + description = self.description + + required = self.required + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "type": type_, + } + ) + if description is not UNSET: + field_dict["description"] = description + if required is not UNSET: + field_dict["required"] = required + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + d = dict(src_dict) + type_ = CustomHTTPParameterType._decode(d.pop("type")) + + description = d.pop("description", UNSET) + + required = d.pop("required", UNSET) + + custom_http_parameter = cls( + type_=type_, + description=description, + required=required, + ) + + return custom_http_parameter diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter_type.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter_type.py new file mode 100644 index 0000000000..2d82dc9ffa --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_parameter_type.py @@ -0,0 +1,31 @@ +from enum import StrEnum + + +class CustomHTTPParameterType(StrEnum): + CUSTOM_HTTP_PARAMETER_TYPE_BOOLEAN = "boolean" + CUSTOM_HTTP_PARAMETER_TYPE_INTEGER = "integer" + CUSTOM_HTTP_PARAMETER_TYPE_NUMBER = "number" + CUSTOM_HTTP_PARAMETER_TYPE_STRING = "string" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def _decode(cls, value: object) -> "CustomHTTPParameterType": + """Reads the value from an answer. A string this client does not list yet is kept as a member of its own, + so an answer from a newer router still reads, and is written back as it came.""" + try: + return cls(value) + except ValueError: + if not isinstance(value, str): + raise + member = str.__new__(cls, value) + member._name_ = value + member._value_ = value + return member + + def __reduce_ex__(self, protocol: object) -> object: + """Pickles a member this client does not list through _decode, as Enum's own reduce would call cls(value).""" + if self._value_ in type(self)._value2member_map_: + return super().__reduce_ex__(protocol) + return type(self)._decode, (self._value_,) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool.py new file mode 100644 index 0000000000..b443982400 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from typing_extensions import Self + +from ..models.custom_http_tool_method import CustomHTTPToolMethod +from ..types import UNSET, Unset + +if TYPE_CHECKING: + from ..models.custom_http_tool_parameters import CustomHTTPToolParameters + + +T = TypeVar("T", bound="CustomHTTPTool") + + +@_attrs_define +class CustomHTTPTool: + """One tool of an http connector: one request, whose method and path are fixed. + + Attributes: + description (str): What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + method (CustomHTTPToolMethod): + name (str): 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + path (str): Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of + that name, which must be required. + parameters (CustomHTTPToolParameters | Unset): The values the model gives, by name, up to 64. A parameter not in + the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a + method override, such as _method or X-HTTP-Method-Override, is refused. + read_only (bool | Unset): The tool only reads. Only a GET or HEAD tool may say so. + """ + + description: str + method: CustomHTTPToolMethod + name: str + path: str + parameters: CustomHTTPToolParameters | Unset = UNSET + read_only: bool | Unset = UNSET + + def to_dict(self) -> dict[str, Any]: + description = self.description + + method = self.method.value + + name = self.name + + path = self.path + + parameters: dict[str, Any] | Unset = UNSET + if not isinstance(self.parameters, Unset): + parameters = self.parameters.to_dict() + + read_only = self.read_only + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "description": description, + "method": method, + "name": name, + "path": path, + } + ) + if parameters is not UNSET: + field_dict["parameters"] = parameters + if read_only is not UNSET: + field_dict["read_only"] = read_only + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.custom_http_tool_parameters import CustomHTTPToolParameters + + d = dict(src_dict) + description = d.pop("description") + + method = CustomHTTPToolMethod._decode(d.pop("method")) + + name = d.pop("name") + + path = d.pop("path") + + _parameters = d.pop("parameters", UNSET) + parameters: CustomHTTPToolParameters | Unset + if isinstance(_parameters, Unset): + parameters = UNSET + else: + parameters = CustomHTTPToolParameters.from_dict(_parameters) + + read_only = d.pop("read_only", UNSET) + + custom_http_tool = cls( + description=description, + method=method, + name=name, + path=path, + parameters=parameters, + read_only=read_only, + ) + + return custom_http_tool diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_method.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_method.py new file mode 100644 index 0000000000..5c52e76f1f --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_method.py @@ -0,0 +1,33 @@ +from enum import StrEnum + + +class CustomHTTPToolMethod(StrEnum): + CUSTOM_HTTP_TOOL_METHOD_DELETE = "DELETE" + CUSTOM_HTTP_TOOL_METHOD_GET = "GET" + CUSTOM_HTTP_TOOL_METHOD_HEAD = "HEAD" + CUSTOM_HTTP_TOOL_METHOD_PATCH = "PATCH" + CUSTOM_HTTP_TOOL_METHOD_POST = "POST" + CUSTOM_HTTP_TOOL_METHOD_PUT = "PUT" + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def _decode(cls, value: object) -> "CustomHTTPToolMethod": + """Reads the value from an answer. A string this client does not list yet is kept as a member of its own, + so an answer from a newer router still reads, and is written back as it came.""" + try: + return cls(value) + except ValueError: + if not isinstance(value, str): + raise + member = str.__new__(cls, value) + member._name_ = value + member._value_ = value + return member + + def __reduce_ex__(self, protocol: object) -> object: + """Pickles a member this client does not list through _decode, as Enum's own reduce would call cls(value).""" + if self._value_ in type(self)._value2member_map_: + return super().__reduce_ex__(protocol) + return type(self)._decode, (self._value_,) diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_parameters.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_parameters.py new file mode 100644 index 0000000000..72fdb18565 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_http_tool_parameters.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from attrs import field as _attrs_field +from typing_extensions import Self + +if TYPE_CHECKING: + from ..models.custom_http_parameter import CustomHTTPParameter + + +T = TypeVar("T", bound="CustomHTTPToolParameters") + + +@_attrs_define +class CustomHTTPToolParameters: + """The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or + DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method- + Override, is refused. + + """ + + additional_properties: dict[str, CustomHTTPParameter] = _attrs_field( + init=False, factory=dict + ) + + def to_dict(self) -> dict[str, Any]: + + field_dict: dict[str, Any] = {} + for prop_name, prop in self.additional_properties.items(): + field_dict[prop_name] = prop.to_dict() + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.custom_http_parameter import CustomHTTPParameter + + d = dict(src_dict) + custom_http_tool_parameters = cls() + + additional_properties = {} + for prop_name, prop_dict in d.items(): + additional_property = CustomHTTPParameter.from_dict(prop_dict) + + additional_properties[prop_name] = additional_property + + custom_http_tool_parameters.additional_properties = additional_properties + return custom_http_tool_parameters + + @property + def additional_keys(self) -> list[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> CustomHTTPParameter: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: CustomHTTPParameter) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_httpapi.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_httpapi.py new file mode 100644 index 0000000000..25dfaee1b0 --- /dev/null +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/custom_httpapi.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, TypeVar + +from attrs import define as _attrs_define +from typing_extensions import Self + +if TYPE_CHECKING: + from ..models.custom_http_tool import CustomHTTPTool + + +T = TypeVar("T", bound="CustomHTTPAPI") + + +@_attrs_define +class CustomHTTPAPI: + """An HTTP API a custom connector calls, and the tools it offers an agent. + + Attributes: + base_url (str): The API the tools call, each at its path under it: a public https URL without userinfo, query or + fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + tools (list[CustomHTTPTool]): At least one and at most 128, each name once. + """ + + base_url: str + tools: list[CustomHTTPTool] + + def to_dict(self) -> dict[str, Any]: + base_url = self.base_url + + tools = [] + for tools_item_data in self.tools: + tools_item = tools_item_data.to_dict() + tools.append(tools_item) + + field_dict: dict[str, Any] = {} + + field_dict.update( + { + "base_url": base_url, + "tools": tools, + } + ) + + return field_dict + + @classmethod + def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: + from ..models.custom_http_tool import CustomHTTPTool + + d = dict(src_dict) + base_url = d.pop("base_url") + + tools = [] + _tools = d.pop("tools") + for tools_item_data in _tools: + tools_item = CustomHTTPTool.from_dict(tools_item_data) + + tools.append(tools_item) + + custom_httpapi = cls( + base_url=base_url, + tools=tools, + ) + + return custom_httpapi diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs index 1b84fb7883..5de6188d4c 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -7008,7 +7008,7 @@ public System.Collections.Generic.IDictionary AdditionalProperti } /// - /// A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. + /// A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. /// [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class CustomConnectorRequest @@ -7024,10 +7024,16 @@ public partial class CustomConnectorRequest public string? Description { get; set; } = default!; /// - /// The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. + /// The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. /// [System.Text.Json.Serialization.JsonPropertyName("endpoint")] - public string Endpoint { get; set; } = default!; + public string? Endpoint { get; set; } = default!; + + /// + /// An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. + /// + [System.Text.Json.Serialization.JsonPropertyName("http")] + public CustomHTTPAPI? Http { get; set; } = default!; /// /// Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. @@ -7052,6 +7058,96 @@ public partial class CustomConnectorRequest } + /// + /// An HTTP API a custom connector calls, and the tools it offers an agent. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class CustomHTTPAPI + { + + /// + /// The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + /// + [System.Text.Json.Serialization.JsonPropertyName("base_url")] + public string BaseUrl { get; set; } = default!; + + /// + /// At least one and at most 128, each name once. + /// + [System.Text.Json.Serialization.JsonPropertyName("tools")] + public System.Collections.Generic.List Tools { get; set; } = new System.Collections.Generic.List(); + + } + + /// + /// One value the model gives an http tool. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class CustomHTTPParameter + { + + [System.Text.Json.Serialization.JsonPropertyName("description")] + public string? Description { get; set; } = default!; + + /// + /// The model must give it. A parameter in the path must be required. + /// + [System.Text.Json.Serialization.JsonPropertyName("required")] + public bool? Required { get; set; } = default!; + + /// + /// One of `string`, `number`, `integer`, `boolean`. + /// + [System.Text.Json.Serialization.JsonPropertyName("type")] + public string Type { get; set; } = default!; + + } + + /// + /// One tool of an http connector: one request, whose method and path are fixed. + /// + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] + public partial class CustomHTTPTool + { + + /// + /// What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + /// + [System.Text.Json.Serialization.JsonPropertyName("description")] + public string Description { get; set; } = default!; + + /// + /// One of `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`. + /// + [System.Text.Json.Serialization.JsonPropertyName("method")] + public string Method { get; set; } = default!; + + /// + /// 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + /// + [System.Text.Json.Serialization.JsonPropertyName("name")] + public string Name { get; set; } = default!; + + /// + /// The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + /// + [System.Text.Json.Serialization.JsonPropertyName("parameters")] + public System.Collections.Generic.Dictionary? Parameters { get; set; } = default!; + + /// + /// Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + /// + [System.Text.Json.Serialization.JsonPropertyName("path")] + public string Path { get; set; } = default!; + + /// + /// The tool only reads. Only a GET or HEAD tool may say so. + /// + [System.Text.Json.Serialization.JsonPropertyName("read_only")] + public bool? ReadOnly { get; set; } = default!; + + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0))")] public partial class CustomModel { diff --git a/sdks/go/acceleration/enums_test.go b/sdks/go/acceleration/enums_test.go index 8f88fedd08..1375c5f195 100644 --- a/sdks/go/acceleration/enums_test.go +++ b/sdks/go/acceleration/enums_test.go @@ -24,3 +24,39 @@ func TestAgentLogSourceKeepsItsConstantNames(t *testing.T) { } } } + +// TestInvocationArgumentTypeKeepsItsConstantNames pins the names v0.5.1 released, which +// CustomHTTPParameterType's string, number and boolean would rename the same way. +func TestInvocationArgumentTypeKeepsItsConstantNames(t *testing.T) { + named := map[acceleration.InvocationArgumentType]string{ + acceleration.Array: "array", + acceleration.Boolean: "boolean", + acceleration.Null: "null", + acceleration.Number: "number", + acceleration.Object: "object", + acceleration.String: "string", + } + for constant, value := range named { + if string(constant) != value { + t.Errorf("%q is spelled %q", value, constant) + } + } +} + +// TestCustomHTTPToolMethodNamesItsConstants pins prefixed names for the http methods, so the +// next enum with GET or POST in it renames nothing callers already use. +func TestCustomHTTPToolMethodNamesItsConstants(t *testing.T) { + named := map[acceleration.CustomHTTPToolMethod]string{ + acceleration.CustomHTTPToolMethodGET: "GET", + acceleration.CustomHTTPToolMethodHEAD: "HEAD", + acceleration.CustomHTTPToolMethodPOST: "POST", + acceleration.CustomHTTPToolMethodPUT: "PUT", + acceleration.CustomHTTPToolMethodPATCH: "PATCH", + acceleration.CustomHTTPToolMethodDELETE: "DELETE", + } + for constant, value := range named { + if string(constant) != value { + t.Errorf("%q is spelled %q", value, constant) + } + } +} diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 282cd0efcd..1bb37481f3 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -1099,6 +1099,60 @@ func (e CreditEntryKind) Valid() bool { } } +// Defines values for CustomHTTPParameterType. +const ( + CustomHTTPParameterTypeBoolean CustomHTTPParameterType = "boolean" + CustomHTTPParameterTypeInteger CustomHTTPParameterType = "integer" + CustomHTTPParameterTypeNumber CustomHTTPParameterType = "number" + CustomHTTPParameterTypeString CustomHTTPParameterType = "string" +) + +// Valid indicates whether the value is a known member of the CustomHTTPParameterType enum. +func (e CustomHTTPParameterType) Valid() bool { + switch e { + case CustomHTTPParameterTypeBoolean: + return true + case CustomHTTPParameterTypeInteger: + return true + case CustomHTTPParameterTypeNumber: + return true + case CustomHTTPParameterTypeString: + return true + default: + return false + } +} + +// Defines values for CustomHTTPToolMethod. +const ( + CustomHTTPToolMethodDELETE CustomHTTPToolMethod = "DELETE" + CustomHTTPToolMethodGET CustomHTTPToolMethod = "GET" + CustomHTTPToolMethodHEAD CustomHTTPToolMethod = "HEAD" + CustomHTTPToolMethodPATCH CustomHTTPToolMethod = "PATCH" + CustomHTTPToolMethodPOST CustomHTTPToolMethod = "POST" + CustomHTTPToolMethodPUT CustomHTTPToolMethod = "PUT" +) + +// Valid indicates whether the value is a known member of the CustomHTTPToolMethod enum. +func (e CustomHTTPToolMethod) Valid() bool { + switch e { + case CustomHTTPToolMethodDELETE: + return true + case CustomHTTPToolMethodGET: + return true + case CustomHTTPToolMethodHEAD: + return true + case CustomHTTPToolMethodPATCH: + return true + case CustomHTTPToolMethodPOST: + return true + case CustomHTTPToolMethodPUT: + return true + default: + return false + } +} + // Defines values for CustomModelRequestTrainsOnData. const ( CustomModelRequestTrainsOnDataNo CustomModelRequestTrainsOnData = "no" @@ -6487,7 +6541,7 @@ type CreditPage struct { NextCursor *string `json:"next_cursor,omitempty"` } -// CustomConnectorRequest A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. +// CustomConnectorRequest A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. type CustomConnectorRequest struct { Category *string `json:"category,omitempty"` @@ -6495,8 +6549,11 @@ type CustomConnectorRequest struct { Client *ConnectorClient `json:"client,omitempty"` Description *string `json:"description,omitempty"` - // Endpoint The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. - Endpoint string `json:"endpoint"` + // Endpoint The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. + Endpoint *string `json:"endpoint,omitempty"` + + // Http An HTTP API a custom connector calls, and the tools it offers an agent. + Http *CustomHTTPAPI `json:"http,omitempty"` // Id Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. Id string `json:"id"` @@ -6509,6 +6566,49 @@ type CustomConnectorRequest struct { Scopes *[]string `json:"scopes,omitempty"` } +// CustomHTTPAPI An HTTP API a custom connector calls, and the tools it offers an agent. +type CustomHTTPAPI struct { + // BaseUrl The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + BaseUrl string `json:"base_url"` + + // Tools At least one and at most 128, each name once. + Tools []CustomHTTPTool `json:"tools"` +} + +// CustomHTTPParameter One value the model gives an http tool. +type CustomHTTPParameter struct { + Description *string `json:"description,omitempty"` + + // Required The model must give it. A parameter in the path must be required. + Required *bool `json:"required,omitempty"` + Type CustomHTTPParameterType `json:"type"` +} + +// CustomHTTPParameterType defines model for CustomHTTPParameter.Type. +type CustomHTTPParameterType string + +// CustomHTTPTool One tool of an http connector: one request, whose method and path are fixed. +type CustomHTTPTool struct { + // Description What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + Description string `json:"description"` + Method CustomHTTPToolMethod `json:"method"` + + // Name 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + Name string `json:"name"` + + // Parameters The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + Parameters *map[string]CustomHTTPParameter `json:"parameters,omitempty"` + + // Path Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + Path string `json:"path"` + + // ReadOnly The tool only reads. Only a GET or HEAD tool may say so. + ReadOnly *bool `json:"read_only,omitempty"` +} + +// CustomHTTPToolMethod defines model for CustomHTTPTool.Method. +type CustomHTTPToolMethod string + // CustomModel defines model for CustomModel. type CustomModel struct { BaseUrl string `json:"base_url"` @@ -14068,9 +14168,9 @@ type ClientInterface interface { // Corresponds with GET /v1/agents/connectors (the `ListConnectors` operationId). ListConnectors(ctx context.Context, params *ListConnectorsParams, reqEditors ...RequestEditorFn) (*http.Response, error) - // CreateConnectorWithBody Add a custom MCP connector + // CreateConnectorWithBody Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -14079,9 +14179,9 @@ type ClientInterface interface { // Corresponds with POST /v1/agents/connectors (the `CreateConnector` operationId). CreateConnectorWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - // CreateConnector Add a custom MCP connector + // CreateConnector Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -18234,9 +18334,9 @@ func (c *Client) ListConnectors(ctx context.Context, params *ListConnectorsParam return c.Client.Do(req) } -// CreateConnectorWithBody Add a custom MCP connector +// CreateConnectorWithBody Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -18255,9 +18355,9 @@ func (c *Client) CreateConnectorWithBody(ctx context.Context, contentType string return c.Client.Do(req) } -// CreateConnector Add a custom MCP connector +// CreateConnector Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -37353,9 +37453,9 @@ type ClientWithResponsesInterface interface { // Corresponds with GET /v1/agents/connectors (the `ListConnectors` operationId). ListConnectorsWithResponse(ctx context.Context, params *ListConnectorsParams, reqEditors ...RequestEditorFn) (*ListConnectorsResponse, error) - // CreateConnectorWithBodyWithResponse Add a custom MCP connector + // CreateConnectorWithBodyWithResponse Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -37364,9 +37464,9 @@ type ClientWithResponsesInterface interface { // Corresponds with POST /v1/agents/connectors (the `CreateConnector` operationId). CreateConnectorWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateConnectorResponse, error) - // CreateConnectorWithResponse Add a custom MCP connector + // CreateConnectorWithResponse Add a custom connector // - // Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + // Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -69143,9 +69243,9 @@ func (c *ClientWithResponses) ListConnectorsWithResponse(ctx context.Context, pa return ParseListConnectorsResponse(rsp) } -// CreateConnectorWithBodyWithResponse Add a custom MCP connector +// CreateConnectorWithBodyWithResponse Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // @@ -69160,9 +69260,9 @@ func (c *ClientWithResponses) CreateConnectorWithBodyWithResponse(ctx context.Co return ParseCreateConnectorResponse(rsp) } -// CreateConnectorWithResponse Add a custom MCP connector +// CreateConnectorWithResponse Add a custom connector // -// Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. +// Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. // // Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. // diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index 6d87e6bb5f..62b9a1f4a3 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -1130,8 +1130,8 @@ export type paths = { readonly get: operations["listConnectors"]; readonly put?: never; /** - * Add a custom MCP connector - * @description Stores a custom MCP server as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. + * Add a custom connector + * @description Stores a custom MCP server, or an HTTP API and its tools, as one of the app's connectors. Sending an id the app already has stores its next revision, which connections pick up when they reconnect; sending the same definition again changes nothing. A built-in cannot be changed this way. * * Server-side only: it needs a server-side token, so it cannot be reached from an end user's device. */ @@ -7197,13 +7197,15 @@ export type components = { readonly items: readonly components["schemas"]["CreditEntry"][]; readonly next_cursor?: string; }; - /** @description A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. */ + /** @description A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. */ readonly CustomConnectorRequest: { readonly category?: string; readonly client?: components["schemas"]["ConnectorClient"]; readonly description?: string; - /** @description The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. */ - readonly endpoint: string; + /** @description The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. */ + readonly endpoint?: string; + /** @description An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. */ + readonly http?: components["schemas"]["CustomHTTPAPI"]; /** @description Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. */ readonly id: string; readonly name: string; @@ -7212,6 +7214,38 @@ export type components = { /** @description The scopes a consent asks for, each an RFC 6749 scope token. */ readonly scopes?: readonly string[] | null; }; + /** @description An HTTP API a custom connector calls, and the tools it offers an agent. */ + readonly CustomHTTPAPI: { + /** @description The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. */ + readonly base_url: string; + /** @description At least one and at most 128, each name once. */ + readonly tools: readonly components["schemas"]["CustomHTTPTool"][]; + }; + /** @description One value the model gives an http tool. */ + readonly CustomHTTPParameter: { + readonly description?: string; + /** @description The model must give it. A parameter in the path must be required. */ + readonly required?: boolean; + /** @enum {string} */ + readonly type: "string" | "number" | "integer" | "boolean"; + }; + /** @description One tool of an http connector: one request, whose method and path are fixed. */ + readonly CustomHTTPTool: { + /** @description What the tool does, which the model reads to know when to use it. Up to 1000 bytes. */ + readonly description: string; + /** @enum {string} */ + readonly method: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE"; + /** @description 1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. */ + readonly name: string; + /** @description The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. */ + readonly parameters?: { + readonly [key: string]: components["schemas"]["CustomHTTPParameter"]; + }; + /** @description Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. */ + readonly path: string; + /** @description The tool only reads. Only a GET or HEAD tool may say so. */ + readonly read_only?: boolean; + }; readonly CustomModel: { readonly base_url: string; /** Format: int64 */ diff --git a/sdks/php/src/Generated/CustomConnectorRequest.php b/sdks/php/src/Generated/CustomConnectorRequest.php index df5cac0e40..d3d86747cc 100644 --- a/sdks/php/src/Generated/CustomConnectorRequest.php +++ b/sdks/php/src/Generated/CustomConnectorRequest.php @@ -9,26 +9,28 @@ use GetStream\VisionAgents\Json; /** - * A custom MCP server for the app's agents to connect to. An unknown field is refused rather - * than ignored. + * A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is + * refused rather than ignored. */ final readonly class CustomConnectorRequest { public function __construct( - // The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on... - public string $endpoint, // Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id... public string $id, public string $name, // How a connection may authenticate. Each must be a scheme this deployment has, except oauth2_client_credenti... /** @var list */ public array $schemes, + // The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on... + public ?string $endpoint = null, public ?string $category = null, public ?ConnectorClient $client = null, public ?string $description = null, // The scopes a consent asks for, each an RFC 6749 scope token. /** @var list|null */ public ?array $scopes = null, + // An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. + public ?CustomHTTPAPI $http = null, ) { } @@ -38,14 +40,15 @@ public function __construct( public static function fromArray(array $data): self { return new self( - endpoint: Json::string($data, 'endpoint'), id: Json::string($data, 'id'), name: Json::string($data, 'name'), schemes: Json::strings($data, 'schemes'), + endpoint: array_key_exists('endpoint', $data) && $data['endpoint'] !== null ? Json::string($data, 'endpoint') : null, category: array_key_exists('category', $data) && $data['category'] !== null ? Json::string($data, 'category') : null, client: array_key_exists('client', $data) && $data['client'] !== null ? ConnectorClient::fromArray(Json::object($data, 'client')) : null, description: array_key_exists('description', $data) && $data['description'] !== null ? Json::string($data, 'description') : null, scopes: array_key_exists('scopes', $data) && $data['scopes'] !== null ? Json::strings($data, 'scopes') : null, + http: array_key_exists('http', $data) && $data['http'] !== null ? CustomHTTPAPI::fromArray(Json::object($data, 'http')) : null, ); } @@ -57,10 +60,12 @@ public static function fromArray(array $data): self public function toArray(): array { $out = []; - $out['endpoint'] = $this->endpoint; $out['id'] = $this->id; $out['name'] = $this->name; $out['schemes'] = $this->schemes; + if ($this->endpoint !== null) { + $out['endpoint'] = $this->endpoint; + } if ($this->category !== null) { $out['category'] = $this->category; } @@ -73,6 +78,9 @@ public function toArray(): array if ($this->scopes !== null) { $out['scopes'] = $this->scopes; } + if ($this->http !== null) { + $out['http'] = $this->http->toArray(); + } return $out; } } diff --git a/sdks/php/src/Generated/CustomHTTPAPI.php b/sdks/php/src/Generated/CustomHTTPAPI.php new file mode 100644 index 0000000000..83a4e3c8a6 --- /dev/null +++ b/sdks/php/src/Generated/CustomHTTPAPI.php @@ -0,0 +1,48 @@ + */ + public array $tools, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + baseUrl: Json::string($data, 'base_url'), + tools: array_map(CustomHTTPTool::fromArray(...), Json::objects($data, 'tools')), + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['base_url'] = $this->baseUrl; + $out['tools'] = array_map(static fn (CustomHTTPTool $each): array => $each->toArray(), $this->tools); + return $out; + } +} diff --git a/sdks/php/src/Generated/CustomHTTPParameter.php b/sdks/php/src/Generated/CustomHTTPParameter.php new file mode 100644 index 0000000000..bbb34335b8 --- /dev/null +++ b/sdks/php/src/Generated/CustomHTTPParameter.php @@ -0,0 +1,53 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self( + type: Json::string($data, 'type'), + description: array_key_exists('description', $data) && $data['description'] !== null ? Json::string($data, 'description') : null, + required: array_key_exists('required', $data) && $data['required'] !== null ? Json::bool($data, 'required') : null, + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['type'] = $this->type; + if ($this->description !== null) { + $out['description'] = $this->description; + } + if ($this->required !== null) { + $out['required'] = $this->required; + } + return $out; + } +} diff --git a/sdks/php/src/Generated/CustomHTTPTool.php b/sdks/php/src/Generated/CustomHTTPTool.php new file mode 100644 index 0000000000..905a47b4d7 --- /dev/null +++ b/sdks/php/src/Generated/CustomHTTPTool.php @@ -0,0 +1,67 @@ +|null */ + public ?array $parameters = null, + // The tool only reads. Only a GET or HEAD tool may say so. + public ?bool $readOnly = null, + ) { + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self( + description: Json::string($data, 'description'), + method: Json::string($data, 'method'), + name: Json::string($data, 'name'), + path: Json::string($data, 'path'), + parameters: array_key_exists('parameters', $data) && $data['parameters'] !== null ? Json::object($data, 'parameters') : null, + readOnly: array_key_exists('read_only', $data) && $data['read_only'] !== null ? Json::bool($data, 'read_only') : null, + ); + } + + /** + * The request body, leaving out every field that was not set. + * + * @return array + */ + public function toArray(): array + { + $out = []; + $out['description'] = $this->description; + $out['method'] = $this->method; + $out['name'] = $this->name; + $out['path'] = $this->path; + if ($this->parameters !== null) { + $out['parameters'] = Json::objectValue($this->parameters); + } + if ($this->readOnly !== null) { + $out['read_only'] = $this->readOnly; + } + return $out; + } +} diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb index 2496d3a998..774477ff1b 100644 --- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb +++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb @@ -2432,8 +2432,20 @@ module Generated required: %w[items has_more].freeze, open: false }.freeze, "CustomConnectorRequest" => { - properties: %w[category client description endpoint id name schemes scopes].freeze, - required: %w[id name endpoint schemes].freeze, open: false + properties: %w[category client description endpoint http id name schemes scopes].freeze, + required: %w[id name schemes].freeze, open: false + }.freeze, + "CustomHTTPAPI" => { + properties: %w[base_url tools].freeze, + required: %w[base_url tools].freeze, open: false + }.freeze, + "CustomHTTPParameter" => { + properties: %w[description required type].freeze, + required: %w[type].freeze, open: false + }.freeze, + "CustomHTTPTool" => { + properties: %w[description method name parameters path read_only].freeze, + required: %w[name description method path].freeze, open: false }.freeze, "CustomModel" => { properties: %w[base_url context_window created_at has_api_key id input_modalities model name per_million_input_tokens per_million_output_tokens retention target trains_on_data updated_at].freeze, diff --git a/sdks/rust/src/operations.rs b/sdks/rust/src/operations.rs index 5432840eb2..7e7f753f9b 100644 --- a/sdks/rust/src/operations.rs +++ b/sdks/rust/src/operations.rs @@ -951,7 +951,7 @@ impl Client { ) .await } - /// Add a custom MCP connector + /// Add a custom connector /// /// `POST /v1/agents/connectors` (`createConnector`). pub async fn create_connector( diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs index b90d80196e..50c1760691 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -5275,7 +5275,7 @@ pub struct CreditPage { #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub next_cursor: ::std::option::Option<::std::string::String>, } -///A custom MCP server for the app's agents to connect to. An unknown field is refused rather than ignored. +///A custom MCP server or HTTP API for the app's agents to connect to. An unknown field is refused rather than ignored. #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] #[serde(deny_unknown_fields)] #[derive(Default)] @@ -5286,8 +5286,12 @@ pub struct CustomConnectorRequest { pub client: ::std::option::Option, #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub description: ::std::option::Option<::std::string::String>, - ///The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. - pub endpoint: ::std::string::String, + ///The MCP server, over Streamable HTTP: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Set this or http, not both. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub endpoint: ::std::option::Option<::std::string::String>, + ///An HTTP API whose tools the connector lists itself, in place of an MCP server. Set this or endpoint, not both. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub http: ::std::option::Option, ///Starts with custom_, which no built-in does, so a custom definition never stands in for one. Creating an id that exists stores the next revision, unless the newest already says the same. pub id: ::std::string::String, pub name: ::std::string::String, @@ -5298,6 +5302,165 @@ pub struct CustomConnectorRequest { #[serde(skip_serializing_if = "::std::option::Option::is_none")] pub scopes: ::std::option::Option<::std::vec::Vec<::std::string::String>>, } +///One value the model gives an http tool. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct CustomHttpParameter { + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub description: ::std::option::Option<::std::string::String>, + ///The model must give it. A parameter in the path must be required. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub required: ::std::option::Option, + #[serde(rename = "type")] + pub type_: CustomHttpParameterType, +} +///`CustomHttpParameterType` +#[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, +)] +pub enum CustomHttpParameterType { + #[serde(rename = "string")] + String, + #[serde(rename = "number")] + Number, + #[serde(rename = "integer")] + Integer, + #[serde(rename = "boolean")] + Boolean, + /// A value this SDK's spec does not list, as the router sent it. + #[serde(untagged)] + Unlisted(::std::string::String), +} +impl ::std::fmt::Display for CustomHttpParameterType { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::String => f.write_str("string"), + Self::Number => f.write_str("number"), + Self::Integer => f.write_str("integer"), + Self::Boolean => f.write_str("boolean"), + Self::Unlisted(ref value) => f.write_str(value), + } + } +} +impl ::std::str::FromStr for CustomHttpParameterType { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "string" => Ok(Self::String), + "number" => Ok(Self::Number), + "integer" => Ok(Self::Integer), + "boolean" => Ok(Self::Boolean), + _ => Err("invalid value".into()), + } + } +} +impl ::std::convert::TryFrom<&str> for CustomHttpParameterType { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } +} +impl ::std::convert::TryFrom<::std::string::String> for CustomHttpParameterType { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } +} +///One tool of an http connector: one request, whose method and path are fixed. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct CustomHttpTool { + ///What the tool does, which the model reads to know when to use it. Up to 1000 bytes. + pub description: ::std::string::String, + pub method: CustomHttpToolMethod, + ///1 to 63 letters, digits, _ or -. The model is offered it after the binding's name and __. + pub name: ::std::string::String, + ///The values the model gives, by name, up to 64. A parameter not in the path goes into the query of a GET, HEAD or DELETE and into a JSON body otherwise. A name a client reads as a method override, such as _method or X-HTTP-Method-Override, is refused. + #[serde( + default, + skip_serializing_if = ":: std :: collections :: BTreeMap::is_empty" + )] + pub parameters: ::std::collections::BTreeMap<::std::string::String, CustomHttpParameter>, + ///Under base_url, starting with /, without a query or fragment. Each {name} in it is the parameter of that name, which must be required. + pub path: ::std::string::String, + ///The tool only reads. Only a GET or HEAD tool may say so. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub read_only: ::std::option::Option, +} +///`CustomHttpToolMethod` +#[derive( + ::serde::Deserialize, ::serde::Serialize, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, +)] +pub enum CustomHttpToolMethod { + #[serde(rename = "GET")] + Get, + #[serde(rename = "HEAD")] + Head, + #[serde(rename = "POST")] + Post, + #[serde(rename = "PUT")] + Put, + #[serde(rename = "PATCH")] + Patch, + #[serde(rename = "DELETE")] + Delete, + /// A value this SDK's spec does not list, as the router sent it. + #[serde(untagged)] + Unlisted(::std::string::String), +} +impl ::std::fmt::Display for CustomHttpToolMethod { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + match *self { + Self::Get => f.write_str("GET"), + Self::Head => f.write_str("HEAD"), + Self::Post => f.write_str("POST"), + Self::Put => f.write_str("PUT"), + Self::Patch => f.write_str("PATCH"), + Self::Delete => f.write_str("DELETE"), + Self::Unlisted(ref value) => f.write_str(value), + } + } +} +impl ::std::str::FromStr for CustomHttpToolMethod { + type Err = self::error::ConversionError; + fn from_str(value: &str) -> ::std::result::Result { + match value { + "GET" => Ok(Self::Get), + "HEAD" => Ok(Self::Head), + "POST" => Ok(Self::Post), + "PUT" => Ok(Self::Put), + "PATCH" => Ok(Self::Patch), + "DELETE" => Ok(Self::Delete), + _ => Err("invalid value".into()), + } + } +} +impl ::std::convert::TryFrom<&str> for CustomHttpToolMethod { + type Error = self::error::ConversionError; + fn try_from(value: &str) -> ::std::result::Result { + value.parse() + } +} +impl ::std::convert::TryFrom<::std::string::String> for CustomHttpToolMethod { + type Error = self::error::ConversionError; + fn try_from( + value: ::std::string::String, + ) -> ::std::result::Result { + value.parse() + } +} +///An HTTP API a custom connector calls, and the tools it offers an agent. +#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq)] +#[serde(deny_unknown_fields)] +#[derive(Default)] +pub struct CustomHttpapi { + ///The API the tools call, each at its path under it: a public https URL without userinfo, query or fragment. An address on a private network, loopback or link-local is refused. Never shown once stored. + pub base_url: ::std::string::String, + ///At least one and at most 128, each name once. + pub tools: ::std::vec::Vec, +} ///`CustomModel` #[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug, PartialEq, Default)] pub struct CustomModel {