# Services API

Services represent external platforms and APIs that your agents can access. STACK currently maintains a catalog of 149 services and supports custom connections for HTTPS APIs outside the catalog. Customer credentials are protected with AWS KMS envelope encryption and decrypted in memory only when an authorized retrieval or proxy call needs them.

All endpoints require a bearer credential. Operator keys and user OAuth tokens can use this API. Connection, configuration, and grant changes refuse agent and Passport contexts and require at least the `standard` member role. Revoking an agent's grants remains agent-reachable because it only removes access.

STACK keeps service credentials encrypted and adds the access token only after authorizing a request. When the provider supports renewal, STACK refreshes expired access automatically and stores the replacement before use. Revoked consent pauses the connection and creates one reconnect event.

## List Available Services

### GET /v1/services

Retrieve the full catalog of available services that can be connected. Each service includes its provider key, display name, and whether it supports OAuth or credential-based connection.

```bash
curl https://api.getstack.run/v1/services \
  -H "Authorization: Bearer <access token>"
```

## List Connected Services

### GET /v1/services/connected

Retrieve all services currently connected to your operator account. Includes connection status, verification state, and who connected the service. Credentials are never returned in list responses - use the Credentials API to retrieve them.

```bash
curl https://api.getstack.run/v1/services/connected \
  -H "Authorization: Bearer <access token>"
```

## Connect a Catalog Service

### POST /v1/services/connect

Connect a service from the catalog. Provide the service ID, desired scopes, and optionally an OAuth token (for OAuth services) or redirect URI.

```bash
curl -X POST https://api.getstack.run/v1/services/connect \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{
    "service_id": "svc_slack",
    "scopes": ["channels:read", "chat:write"],
    "redirect_uri": "https://getstack.run/api/oauth/callback"
  }'
```

### ConnectServiceInput Fields

- service_id (string, required) - the service ID from the catalog
- scopes (string[], required) - at least one scope must be specified
- redirect_uri (string, optional) - OAuth redirect URI
- allowed_hosts (string[], optional) - required for per-tenant hosts that STACK cannot derive
- mcp_url (string, optional) - the address of the MCP endpoint of the service, when it speaks MCP over HTTP: https, on one of the allowed hosts of the connection. stack_service_tools and stack_service_call_tool send their calls there. Omit it for a service that does not speak MCP
- connection_name (string, optional) - what to call this connection: 1-40 characters, letters, digits, spaces and hyphens, unique among your connections of the service without regard to case. Omit it for the first connection of a service (it is named default); a second needs one

The request body can also include `oauth_token` (for completing an OAuth flow) and `member_id` (to attribute the connection to a specific member).

Returns `201` with the created connection object, which carries its `name`. An account can hold several connections of one service. A connect call without a `connection_name`, or with a name an active connection of the service already uses, is refused with `409` once the service has a connection.

## Connect a Custom Service

### POST /v1/services/custom

Connect a custom service that is not in the STACK catalog. Supports both single-field credentials (API key string) and multi-field credentials (key-value pairs). Custom services are private to your account and do not appear in the public catalog.

### Single-field Credential

```bash
curl -X POST https://api.getstack.run/v1/services/custom \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Internal CRM",
    "description": "Company internal CRM API",
    "credential": "crm_key_abc123",
    "scopes": ["read", "write"]
  }'
```

### Multi-field Credential

```bash
curl -X POST https://api.getstack.run/v1/services/custom \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "SFTP Server",
    "description": "Production SFTP for invoice uploads",
    "credential": {
      "host": "sftp.example.com",
      "username": "stack-agent",
      "password": "s3cur3p4ss",
      "port": "22"
    }
  }'
```

### ConnectCustomServiceInput Fields

- name (string, required) - display name, 1-100 chars
- description (string, optional) - human-readable description, max 500 chars
- credential (string | Record\<string, string>, optional) - single API key string or key-value pairs. Optional to allow enabling a service without connecting.
- scopes (string[], optional) - free-form scopes for documentation purposes
- template (string, optional) - if provided, validates credential fields against the named template
- oauth_auth_url (string, optional) - custom OAuth authorization URL
- oauth_token_url (string, optional) - custom OAuth token URL
- allowed_hosts (string[], optional) - hosts that may receive this credential. Required when STACK cannot derive a host.
- mcp_url (string, optional) - the address of the MCP endpoint of the service, when it speaks MCP over HTTP: https, on one of the allowed hosts of the connection. stack_service_tools and stack_service_call_tool send their calls there. Omit it for a service that does not speak MCP
- connection_name (string, optional) - what to call this connection: 1-40 characters, letters, digits, spaces and hyphens, unique among your connections of the service without regard to case. Omit it for the first connection of a service (it is named default); a second needs one

If providing `oauth_auth_url`, you must also provide `oauth_token_url` (and vice versa). They must be provided together.

Custom services are stored with a `custom_` prefix on the provider field (e.g., `custom_internal_crm`). Multi-field credentials are stored as an encrypted JSON string and returned as a `credentials` object on retrieval.

Returns `201` with the created connection object.

## Connect Application Credentials

### POST /v1/services/connect-application

Connect a catalog service with client credentials or another application identity.

- service_id (string, required) - catalog service ID
- credential (object, required) - non-empty application credential fields
- scopes (string[], optional) - granted application scopes
- allowed_hosts (string[], optional) - required for per-tenant hosts that STACK cannot derive
- mcp_url (string, optional) - the address of the MCP endpoint of the service, when it speaks MCP over HTTP: https, on one of the allowed hosts of the connection. stack_service_tools and stack_service_call_tool send their calls there. Omit it for a service that does not speak MCP
- connection_name (string, optional) - what to call this connection: 1-40 characters, letters, digits, spaces and hyphens, unique among your connections of the service without regard to case. Omit it for the first connection of a service (it is named default); a second needs one

## How a Service Connects

There are three ways, and a service can use more than one. A service that has an API key or token connects with it; a company can plug in an OAuth app it registered itself; and STACK runs an OAuth app of its own for Slack and Google only. STACK registers no OAuth app at any other provider.

### With a key or token

Any service you can get a key or token for connects through the connect page or `POST /v1/services/connect-application`, with no app to register. For the services that used to sign in through an app of STACK's, the credential is:

- github - a personal access token (field token)
- linear - an API key (field api_key)
- notion - an internal integration token (field api_key)
- figma - a personal access token (field token)
- discord - a bot token (field bot_token)
- jira and confluence - an Atlassian API token with the site URL and the account email (fields site_url, email, api_token); the key can reach only that site

### With your company's own OAuth app

A company registers an app inside its own organisation, which needs no review by the provider, and gives it to STACK once: `POST /v1/oauth-apps` (owner or admin; the secret is KMS-encrypted and never returned). The redirect URI to give the provider is `https://getstack.run/api/oauth/callback`.

- provider (string, required) - google covers every Google service (Gmail, Drive, Docs, Sheets, Calendar, Analytics, YouTube); microsoft covers Outlook and Teams; any other provider name covers that service. An app saved under a service's own name wins for that service.
- client_id, client_secret (strings, required)
- tenant (string, optional) - the directory of a single-tenant Microsoft app, an id or a verified domain
- scopes (string, optional) - override scopes

Google Workspace: in the Google Cloud console create a project, set the OAuth consent screen user type to Internal, create a Web application OAuth client with the redirect URI above, and save its id and secret under `google`. Microsoft 365: in Microsoft Entra register an application with the single-tenant account type and the redirect URI above (platform Web), create a client secret, and save its id and secret under `microsoft` with the `tenant`. Connections made through Microsoft and Atlassian apps ask for `offline_access`, so they receive a refresh token and renew on their own. A company's own Google app can ask for every scope the service lists, restricted ones included.

### STACK's own apps

Slack keeps its app (chat approvals and Slack connections). STACK's Google app goes through Google's free review, so it asks for no restricted scope: `gmail.send` for Gmail, `drive.file` for Drive (files the app creates or the person picks), `documents` and `spreadsheets` with `drive.file` for Docs and Sheets, `calendar.events` for Calendar, `analytics.readonly` for Analytics and `youtube.upload` for YouTube. Actions that need more (reading an inbox, every file in a Drive, managing calendars, the rest of YouTube) are marked in their descriptions as needing your own Google app.

An agent reads chosen mail when the person forwards it to the agent's own STACK address with a Gmail filter: in Gmail, add the agent's address as a forwarding address, then create a filter that forwards the messages the agent should see.

A connection that was made through an app STACK no longer runs (GitHub, Atlassian, Notion, Linear, Discord or Figma) is not deleted: the first time it is used or verified it reads as reconnect required, with a message saying to reconnect it with an API key or token, or with your own OAuth app.

## Connect Links

### POST /v1/services/connect-links

Connect a catalog service without the credential passing through a chat or a script. The call carries no credential: it returns a one-time link. The person opens it in a browser signed in to STACK, then signs in on the provider's own page or enters the key on a STACK page. The link is bound to your account and member, works once, expires after 10 minutes, and any number can be open at once. STACK stores only a hash of the link, so the URL is returned once.

- service_id (string) - catalog service ID or provider name. Give this or custom, not both
- custom (object) - the own API of the account that takes a key or token: name, allowed_hosts (the hosts the key may be sent to; the page shows them and cannot change them), and optionally description, template and mcp_url (the address of its MCP endpoint, when it speaks MCP over HTTP: https, on one of the hosts). Never a key. OAuth is not supported for a custom service
- scopes (string[], optional) - OAuth scopes to ask for when the service connects through the provider sign-in
- connection_name (string, optional) - what to call the connection the link makes, as in POST /v1/services/connect. A name the account already uses for the service is refused when the link is created. For a custom service it goes inside custom

Returns `201` with `link_id`,`provider`, `method` (`oauth` or`key`), `status`, `expires_at` and`url`. `GET /v1/services/connect-links/:id` returns the status (`pending`, `connected` or `expired`) and the connection id once connected. It never returns the URL or a credential. Agent credentials are refused.

### GET /v1/services/connect-links

Lists the connect links of your account that are still waiting for the person to finish them: status`pending`, not yet expired, newest first, at most 50. Returns`{ links: [...] }`, each link as `GET /v1/services/connect-links/:id`returns it. It never returns a URL or a token. Agent credentials are refused.

## OAuth Token Lifecycle

STACK detects two OAuth token-lifecycle patterns automatically based on the shape of the stored credential JSON. Detection happens at proxy-call and credential-retrieval time. Plain string tokens, API keys, and Basic-auth credentials pass through unchanged.

### 1. Refresh-token rotation (delegated flow)

When a stored credential carries a `refresh_token` field and its `expires_at` is missing or within 60 seconds of the current time, STACK posts a `refresh_token` grant against the connection's`oauth_token_url`, persists the new tokens (KMS-encrypted, with an updated `expires_at`), and only then returns the freshened credential to the caller. The refresh runs under a database row lock on the connection, so concurrent calls share one renewed token and cannot overwrite a rotated refresh token. The token endpoint must be a public HTTPS URL.

Required credential JSON shape:

```json
{
  "access_token": "eyJ0eXAi...",
  "refresh_token": "M.R3_BAY...",
  "expires_at": "2026-04-29T12:34:56.000Z"
}
```

This shape is what the dashboard's OAuth callback already produces — connections made via the standard OAuth dance (Outlook, Gmail, Slack, a company's own app, etc.) get refresh-token rotation transparently with no caller changes.

### 2. Client-credentials grant (application-only / service-account)

When a stored credential carries `client_id` and`client_secret` but no `refresh_token`, and its `access_token` is missing or within 60 seconds of expiry, STACK exchanges them for an application-only access token via the `client_credentials` grant. The token is stored KMS-encrypted on the connection with its `expires_at` and reused until it nears expiry. Tokens are not cached in Redis. No human in the loop, no MFA, no browser — suitable for fully autonomous service-account agents.

Required credential JSON shape (Microsoft Entra example):

```json
{
  "client_id": "<azure-app-client-id>",
  "client_secret": "<azure-app-client-secret>",
  "tenant_id": "<your-entra-tenant-id>",
  "cc_scope": "https://graph.microsoft.com/.default",
  "cc_token_url": "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
}
```

- cc_scope (string, required) — OAuth scope for the grant. Microsoft pattern: "\<resource>/.default" (e.g. https://graph.microsoft.com/.default).
- cc_token_url (string, optional) — token endpoint override. If absent, falls back to the connection's oauth_token_url. STACK substitutes {tenant_id} into /common/ paths automatically when tenant_id is present.
- tenant_id (string, optional) — used for tenant-scoped Microsoft endpoints; non-Microsoft providers can omit.

### Worked example: Microsoft Entra app sending mail as a service account

Suppose an agent needs to send mail as`agent@example.com` with no human in the loop. The setup:

- 1. Register an Azure App (Microsoft Entra) with application permission Mail.Send. Have an admin grant tenant-wide consent.
- 2. Get client_id, client_secret, tenant_id from the app registration.
- 3. Connect to STACK as a custom service with the JSON shape shown above.
- 4. Grant the agent access to the connection with scope ["Mail.Send"].
- 5. The agent calls /v1/proxy with its passport. STACK obtains an application access token and forwards to graph.microsoft.com/v1.0/users/{userId}/sendMail.
- 6. Disconnect the connection to revoke access. The next STACK-verified proxy call fails.

```bash
curl -X POST https://api.getstack.run/v1/services/custom \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Outlook application",
    "credential": {
      "client_id": "your-azure-app-id",
      "client_secret": "your-azure-app-secret",
      "tenant_id": "your-entra-tenant-id",
      "cc_scope": "https://graph.microsoft.com/.default",
      "cc_token_url": "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
    },
    "scopes": ["Mail.Send"]
  }'
```

A failed renewal never replaces the stored credential. If the provider rejects the grant (`invalid_grant`, `invalid_client`,`unauthorized_client`, `token_revoked` or`invalid_refresh_token`), or the credential cannot be renewed at all, STACK marks the connection expired and unhealthy, records one reconnect event and refuses later calls without contacting the provider until the service is reconnected. Any other failure (network error, provider outage, malformed response) fails the call with`409 CONFLICT` before the upstream request is made, and STACK waits 30 seconds before it tries the provider again.

## Disconnect a Service

### DELETE /v1/services/:id/disconnect

Disconnect a service and permanently delete its stored credentials. This also cascades: any agents with grants to this connection have their active passports revoked.

```bash
curl -X DELETE https://api.getstack.run/v1/services/conn_abc123/disconnect \
  -H "Authorization: Bearer <access token>"
```

Disconnecting deletes the stored credential and marks active Passports for affected agents as revoked. The next STACK-verified call rejects those Passports. Any workflow that depends on the connection will fail until it is reconnected.

## Verify a Connection

### POST /v1/services/:id/verify

Test that a service connection is working by making a health check request against the service API. For services with credential templates, STACK uses the template's verification URL. For OAuth services, STACK calls a known "me" endpoint (e.g., Slack's `auth.test`, GitHub's `/user`).

```bash
curl -X POST https://api.getstack.run/v1/services/conn_abc123/verify \
  -H "Authorization: Bearer <access token>"
```

Returns the verification result with status `healthy` or an error. Updates the `verification_status` and `verified_at` columns on the connection.

```json
{
  "status": "healthy",
  "verified_at": "2026-04-15T10:35:00Z"
}
```

## Grant Agent Access to a Service

### POST /v1/services/grant

Grant an agent access to a specific service connection with scoped permissions. The scopes must be a subset of the connection's scopes. The grant also sets the maximum cross-service data flow that future Passports may carry.

```bash
curl -X POST https://api.getstack.run/v1/services/grant \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "agt_abc123",
    "service_connection_id": "conn_abc123",
    "scopes": ["channels:read", "chat:write"]
  }'
```

### GrantAgentAccessInput Fields

- agent_id (string, required) - the agent to grant access to
- service_connection_id (string, required) - the service connection ID
- scopes (string[], required) - at least one scope, must be a subset of the connection scopes
- constraints (array, optional) - parameter limits that passports may tighten but not loosen
- intents (array, optional) - intent references expanded into constraints
- alternatives (array, optional) - several rules on this connection, any one of which allows a call, for example a read rule and a post rule. Each rule is {intents?, constraints?} and must hold in full; the intents and constraints given beside the rules apply to every rule. A call that fits no rule is refused.
- allow_data_from (string[], optional) - service names whose data may flow into this service. Omitted or [] allows no cross-service flow. Two connections of one service are two sources: name the service itself to let content move between its connections, or a connection as service@connection_id to allow one. ["*"] is a standing grant covering the agent's currently active service grants; Passport issuance resolves it to exact names and never signs the wildcard.

A Passport may inherit or narrow this list, but cannot add another source. Adding a source to an existing grant is a governance action. Bearer API, MCP, and CLI callers receive`403 GOVERNANCE_APPROVAL_REQUIRED`; after a human approves the exact request in the dashboard, the caller retries it with`X-Governance-Approval`. Existing Passports do not change when a grant or service connection changes.

Returns `201` with the created grant object.

With hosted controls on and a policy that lists connections, the grant is made but the agent cannot call the connection until a revision of its policy lists it. The answer then carries a `control_policy` object (`policy_id`, `policy_revision`, `revision_needed` and a message), and a call on the connection is refused with `403 CONTROL_DENIED` reason `connection_not_listed`. Adding it to the policy is a loosening that you approve in a signed-in browser; an agent never changes its own policy.

## Revoke Agent Access

### DELETE /v1/services/agents/:agentId/revoke

Revoke all service grants for an agent. This also cascades: active passports for the agent are revoked since the agent lost its service grants.

```bash
curl -X DELETE https://api.getstack.run/v1/services/agents/agt_abc123/revoke \
  -H "Authorization: Bearer <access token>"
```

```json
{
  "success": true
}
```

## Get Agent Permissions

### GET /v1/agents/:agentId/permissions

Retrieve all service grants for a specific agent, showing which connections and scopes the agent has access to. Each grant carries the `connection_name` of its connection.

```bash
curl https://api.getstack.run/v1/agents/agt_abc123/permissions \
  -H "Authorization: Bearer <access token>"
```

## Rename a Connection

### PATCH /v1/services/:id

Give a connection a new name. Owner or admin only; an agent credential is refused. The name follows the same rules as `connection_name` at connect time, and one already used by another active connection of the same service is refused with `409`. Returns the connection.

```bash
curl -X PATCH https://api.getstack.run/v1/services/conn_abc123 \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{ "connection_name": "work" }'
```

## Toggle Proxy Access

### POST /v1/services/:id/proxy-toggle

Enable or disable proxy access for a specific service connection. When proxy is enabled, agents can use the Proxy API to make authenticated requests through STACK without accessing the raw credential.

```bash
curl -X POST https://api.getstack.run/v1/services/conn_abc123/proxy-toggle \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{ "proxy_enabled": true }'
```

### Request Body

- proxy_enabled (boolean, required) - true to enable proxy, false to disable

## Configure Service Mode

### POST /v1/services/configure

Configure how a service connection is shared within the organization. The mode controls whether a single connection is shared across all members or each member has their own.

```bash
curl -X POST https://api.getstack.run/v1/services/configure \
  -H "Authorization: Bearer <access token>" \
  -H "Content-Type: application/json" \
  -d '{
    "service_id": "svc_slack",
    "provider": "slack",
    "mode": "per_member"
  }'
```

### Request Body

- service_id (string, required) - the service ID
- provider (string, required) - the provider slug
- mode (enum, required) - "shared" | "per_member"

## List Service Configurations

### GET /v1/services/configurations

Retrieve all service configurations for your organization, showing the sharing mode for each configured service.

```bash
curl https://api.getstack.run/v1/services/configurations \
  -H "Authorization: Bearer <access token>"
```

## Delete Service Configuration

### DELETE /v1/services/configurations/:provider

Remove the service configuration for a provider, reverting it to default behavior.

```bash
curl -X DELETE https://api.getstack.run/v1/services/configurations/slack \
  -H "Authorization: Bearer <access token>"
```

## List Credential Templates

### GET /v1/services/templates

Retrieve all available credential templates. Templates define the fields required to connect a service, along with help URLs and verification endpoint configurations.

```bash
curl https://api.getstack.run/v1/services/templates \
  -H "Authorization: Bearer <access token>"
```

```json
{
  "templates": [
    {
      "provider": "openai",
      "name": "OpenAI",
      "fields": [
        {
          "key": "api_key",
          "label": "API Key",
          "type": "password",
          "required": true,
          "placeholder": "sk-proj-..."
        }
      ],
      "help_url": "https://platform.openai.com/api-keys",
      "verification_url": "https://api.openai.com/v1/models",
      "verification_headers": {
        "Authorization": "Bearer {{api_key}}"
      }
    }
  ]
}
```

Template field values use `{{field_key}}` interpolation in verification headers and URLs. When verifying a connection, STACK substitutes the actual credential values and checks for a 2xx response.

## Tier Limits

Service connections are unlimited on every tier. Connecting one does not use the shared monthly action allowance.

## Endpoint Summary

```text
GET    /v1/services                          - list catalog services
GET    /v1/services/connected                - list your connections
GET    /v1/services/templates                - list credential templates
GET    /v1/services/configurations           - list service configurations
POST   /v1/services/connect                  - connect a catalog service
POST   /v1/services/connect-application      - connect with application credentials
POST   /v1/services/custom                   - connect a custom service
POST   /v1/services/connect-links            - create a one-time connect link
GET    /v1/services/connect-links            - list the connect links still waiting
GET    /v1/services/connect-links/:id        - read a connect link's status
POST   /v1/services/configure                - set service sharing mode
POST   /v1/services/grant                    - grant agent access
PATCH  /v1/services/:id                      - rename a connection
POST   /v1/services/:id/verify              - verify a connection
POST   /v1/services/:id/proxy-toggle        - toggle proxy access
POST   /v1/services/:id/allowed-hosts       - replace the connection host allowlist
DELETE /v1/services/:id/disconnect           - disconnect a service
DELETE /v1/services/agents/:agentId/revoke   - revoke agent grants
DELETE /v1/services/configurations/:provider - delete configuration
GET    /v1/agents/:agentId/permissions       - get agent service permissions
```
