Everything an AI agent can do with the Sourcegraph API.

A reference guide for building AI agents: every method, how to authenticate, and the permissions each one needs.

Endpoints18
AuthenticationAccess token
Last updated23 June 2026
Orientation

How the Sourcegraph API works.

The Sourcegraph API is how an app or AI agent works with a code intelligence instance: searching code across every connected repository, reading files, looking up users and organizations, and running large-scale code changes. Access comes from an access token that inherits the full permissions of the user who created it, so an agent reaches exactly the repositories and admin actions that user can, with no narrower per-operation scopes. The schema ships with each release and can change between them.

18Endpoints
7Capability groups
9Read
9Write
0Permissions
Authentication
Every request needs an access token, created under Settings then Access tokens, and sent as 'Authorization: token '. An OAuth token from an app with the user:all scope is sent as 'Authorization: Bearer ' instead. A site administrator can create a token with the site-admin:sudo scope to impersonate another user, sent as 'Authorization: token-sudo user="USERNAME",token=""'.
Permissions
There are no granular per-operation scopes. An access token inherits the full permissions of the user who created it, so a regular user's token can do only what that user can, and a site administrator's token can call admin-only operations such as creating and deleting users. The single optional scope, site-admin:sudo, only governs whether a token may impersonate other users; it does not narrow what the token can reach. Repository visibility is enforced by the user's own repository permissions.
Surface
The primary surface is one GraphQL endpoint at /.api/graphql, where every operation is a POST carrying a query or mutation. A separate streaming search route at /.api/search/stream returns matches over server-sent events as they are found, for responsive search. The GraphQL API is documented as intended mainly for debugging and scripting, with the stream API recommended for production search integrations.
Versioning
The GraphQL schema has no dated version string. It ships with each Sourcegraph release and has no backwards-compatibility guarantee across releases, so an integration tracks the schema of the instance version it runs against. The freshness badge shows Current because there is no version date to pin.
Connect & authenticate

Connection & authentication methods.

How an app or AI agent connects to Sourcegraph determines what it can reach. There are several routes, each governed by the access token behind it and the permissions that token inherits from its user.

Ways to connect

GraphQL API

The GraphQL API answers at /.api/graphql on an instance, where every operation is a POST carrying a query or mutation. It is documented as intended mainly for debugging and scripting, with no backwards-compatibility guarantee across Sourcegraph releases.

Best forConnecting an app or AI agent to Sourcegraph.
Governed byThe access token and the permissions it inherits from its user.
Docs ↗

Stream Search API

The Stream Search API answers at /.api/search/stream and returns matches over server-sent events as they are found. Sourcegraph recommends it over GraphQL for production code search integrations.

Best forResponsive code search in an app or AI agent.
Governed byAn access token with the user:all scope.
Docs ↗

MCP server (Model Context Protocol)

Sourcegraph's official MCP server gives an AI agent cross-repository code intelligence over the Model Context Protocol. Core tools answer at /.api/mcp, the full suite at /.api/mcp/all, and Deep Search at /.api/mcp/deepsearch, exposing tools such as keyword_search, read_file, list_repos, go_to_definition, and find_references. It is experimental, on Enterprise plans, and authenticates with an access token or OAuth 2.0.

Best forConnecting an AI agent to Sourcegraph's code intelligence.
Governed byAn access token, plus the MCP#ACCESS permission on the user.
Docs ↗
Authentication

Access token

An access token is created under Settings then Access tokens and sent as 'Authorization: token '. It inherits the full permissions of the user who created it, so it can do exactly what that user can and no less.

TokenPersonal access token
Best forConnecting an app or agent as a specific user
Docs ↗

OAuth token (user:all)

An OAuth app issues a user token with the user:all scope, sent as 'Authorization: Bearer '. Like an access token, it acts as the user and inherits that user's permissions.

TokenOAuth user token
Best forUser-login integrations
Docs ↗

Sudo access token

A site administrator can create a token with the site-admin:sudo scope to impersonate another user, sent as 'Authorization: token-sudo user="USERNAME",token=""'. This is the only optional scope, and it governs impersonation rather than narrowing reach.

TokenSite-admin sudo token
Best forActing on behalf of users from a service
Docs ↗
Capability map

What an AI agent can do in Sourcegraph.

The Sourcegraph API is split into areas an agent can act on, such as code search, repositories, files, users, and batch changes. Each area has its own operations, and some reach far more than others, since several are reserved for site administrators.

Code search

2 endpoints

Search code across every connected repository through GraphQL, and stream the same search over server-sent events as matches are found.

Search reaches every repository the token's user can see.
View endpoints

Repositories

2 endpoints

Look up a single repository by name and list the repositories on an instance.

Repository data is read-only here; visibility follows the user's permissions.
View endpoints

Files & blobs

1 endpoint

Read a file's content and metadata at a given revision through the gitBlob field on a repository commit.

Reading a blob returns the full source of that file.
View endpoints

Users & organizations

6 endpoints

Read the current user, look up a user or an organization, and run admin-only operations to create, update, and delete users.

Creating, updating, and deleting users is restricted to site administrators.
View endpoints

Batch changes

4 endpoints

Create batch changes, build and execute a batch spec, and apply a change set across many repositories at once.

Applying a batch change opens or updates pull requests across real repositories.
View endpoints

Code insights & contexts

2 endpoints

List code insight views and create a saved search context that scopes future searches to chosen repositories.

A search context written here changes what later searches cover.
View endpoints

Administration

1 endpoint

Connect a code host as an external service so its repositories are mirrored and searchable.

Adding an external service grants the instance access to a code host with its token.
View endpoints
Endpoint reference

Every Sourcegraph API operation.

Filter by method, access, or permission, or search any path. Select a row for version detail, rate limits, the related webhook event, and the source.

MethodEndpointWhat it doesAccessPermissionVersion
Search code across every connected repository through GraphQL, and stream the same search over server-sent events as matches are found.2

No per-operation scope. Reaches every repository the token's user is permitted to see. The stream search route is recommended for production search.

Acts onsearch result
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Requires a token with the user:all scope, sent as 'Authorization: token ' or 'Authorization: Bearer '. The q parameter holds the query; v=V3 selects the current query syntax.

Acts onsearch result
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Repositories

Look up a single repository by name and list the repositories on an instance.2

Returns null if the token's user cannot see the repository.

Acts onrepository
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Only returns repositories the token's user is permitted to see.

Acts onrepository
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Files & blobs

Read a file's content and metadata at a given revision through the gitBlob field on a repository commit.1

Reached through repository(name).commit(rev).blob(path). Returns the full source of the file, so it is gated by the user's repository permissions.

Acts onfile
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Users & organizations

Read the current user, look up a user or an organization, and run admin-only operations to create, update, and delete users.6

Returns null when the request is unauthenticated. Used to confirm a token works.

Acts onuser
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Visibility of user details follows the instance's user-visibility settings.

Acts onuser
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Site administrators only. The token must belong to a site-admin user; there is no narrower scope for this.

Acts onuser
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Site administrators only. Takes the target user's ID.

Acts onuser
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Site administrators only. A hard delete cannot be undone; a standard delete marks the user and data as deleted.

Acts onuser
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Returns the organization the token's user is permitted to see.

Acts onorganization
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Batch changes

Create batch changes, build and execute a batch spec, and apply a change set across many repositories at once.4

Requires Batch Changes to be enabled on the instance and the user to be permitted to create one.

Acts onbatch change
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Pairs with executeBatchSpec to run the spec server-side.

Acts onbatch spec
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Runs the spec across the matched repositories on the server.

Acts onbatch spec
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Takes an optional publicationStates argument to control which change sets are published. This is the step that changes real repositories.

Acts onbatch change
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Code insights & contexts

List code insight views and create a saved search context that scopes future searches to chosen repositories.2

All input parameters are optional. Available on Sourcegraph 3.35.1 and later.

Acts oninsight view
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Takes the context definition and a list of repository revisions. The resulting spec is formatted as @username/ContextName.

Acts onsearch context
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply

Administration

Connect a code host as an external service so its repositories are mirrored and searchable.1

Site administrators only. The config holds the code host URL and an authentication token, which the instance then holds.

Acts onexternal service
Permission (capability)None required
VersionAvailable since the API’s base version
Webhook eventNone
Rate limitStandard limits apply
No endpoints match those filters.
Webhooks

Webhook events.

Sourcegraph can notify an app or AI agent when a code host changes, such as a new commit or a changed repository. It registers webhooks on the connected code host rather than emitting its own product event stream.

EventWhat it signalsTriggered by
No events match that search.
Rate limits & pagination

Rate limits, pagination & request size.

Sourcegraph limits how much an app or AI agent can ask for through cost-style ceilings on each GraphQL query, set per instance, rather than a fixed requests-per-minute quota.

Request rate

Sourcegraph limits GraphQL queries by cost rather than by a fixed requests-per-minute quota, and the ceilings are set per instance in site configuration. The defaults cap query nesting at a depth of 30 (GraphQLMaxDepth), the number of returned fields at 500,000 (GraphQLMaxFieldCount), and query aliases at 500 (GraphQLMaxAliases), alongside duplicate and unique field-count limits of 500 each. An administrator can raise or lower any of these. The stream search route instead bounds a single search through query parameters such as display, which caps the matches returned.

Pagination

List operations use cursor-based pagination through a first argument for page size and an after cursor for the next page, returning a pageInfo object with endCursor and hasNextPage. The repositories and insightViews queries follow this pattern. The stream search route returns results progressively over server-sent events rather than in pages.

Request size

GraphQL requests and responses are JSON. Response size is bounded by the field-count ceiling rather than a byte limit, and the stream search route caps the matches a single search returns through its display parameter and truncates long lines through max-line-len.

Errors

Status codes & error handling.

The status codes an agent should handle, and what to do about each.

StatusCodeMeaningWhat to do
200GraphQL errors arrayA syntactically valid GraphQL request returns HTTP 200, and any problems, such as a field that could not be resolved or a permission failure, are listed in an errors array in the response body alongside whatever data resolved. A request can partially succeed.Read the errors array on every response, not just the HTTP status, and treat a non-empty array as a failure for the affected fields.
401UnauthorizedThe access token is missing, malformed, or invalid, so the request is not authenticated.Send a valid token in the Authorization header, using the token, Bearer, or token-sudo form.
403ForbiddenThe request is authenticated but the token's user lacks permission for the operation, such as an admin-only mutation called by a non-admin user or a repository the user cannot see.Use a token whose user has the required permission, or a site-admin token for admin-only operations.
400Bad RequestThe GraphQL query is malformed, or it exceeds a cost ceiling such as the maximum depth, field count, or alias count set for the instance.Fix the query syntax, or simplify it to stay under the instance's depth, field-count, and alias limits.
Versioning & freshness

Version history.

The Sourcegraph GraphQL API carries no dated version string. It is a single schema that ships with each Sourcegraph release and can change between releases, so it is treated as a current, evolving API.

Version history

What changed, and when

Latest versionCurrent
CurrentCurrent version
Single evolving schema, shipped per release

The Sourcegraph GraphQL API carries no dated version string. It is one schema that ships with each Sourcegraph release and can change between releases, with no backwards-compatibility guarantee, so it is treated as a current, evolving API rather than a pinned version. The instance's API console shows the live schema for the release it runs.

Migrate: There is no version header to pin; an integration tracks the schema of the Sourcegraph release its instance runs.
What changed
  • The official Sourcegraph MCP server was announced in September 2025 as an experimental Enterprise feature, exposing search, navigation, history, and Deep Search tools over /.api/mcp.
  • Code Insights GraphQL operations, such as the insightViews query, are available on Sourcegraph 3.35.1 and later.
  • Batch Changes added a publicationStates argument to the applyBatchChange and createBatchChange mutations to set the publication state of individual change sets.
2026-04-13Feature update
Batch Changes bulk changeset sync

Batch Changes gained a bulk action to sync changesets, refreshing the state of every change set across a large batch change in a single operation. It was released on Monday 13 April 2026.

What changed
  • Batch Changes now supports syncing changesets as a bulk action across a large batch change.
2026-04-06Feature update
OAuth for Batch Changes on GitHub

Batch Changes added OAuth support for GitHub code hosts, so a user can authorize a batch change without creating a personal access token by hand. It was released on Monday 6 April 2026.

What changed
  • Batch Changes can authenticate to GitHub code hosts over OAuth instead of a manually created token.
2026-03-23Feature update
Full MCP toolset endpoint

The full Sourcegraph MCP toolset became available at /.api/mcp/all, alongside a curated default endpoint, expanding the tools an AI agent can call over the Model Context Protocol. It was released on Monday 23 March 2026.

What changed
  • The full Sourcegraph MCP toolset is exposed at /.api/mcp/all, with a curated default set at /.api/mcp.

An integration tracks the schema of the Sourcegraph release it runs against, since the GraphQL API has no backwards-compatibility guarantee across releases.

Sourcegraph changelog ↗
Questions

Sourcegraph API, answered.

How do I authenticate with the Sourcegraph API?+
Create an access token under Settings then Access tokens, and send it as 'Authorization: token ' on each request. A token from an OAuth app with the user:all scope is sent as 'Authorization: Bearer ' instead. A site administrator can also create a token with the site-admin:sudo scope and impersonate a user with the 'Authorization: token-sudo user="USERNAME",token=""' header. The GraphQL endpoint is /.api/graphql on the instance.
What permissions does an access token have?+
There are no granular per-operation scopes. A token inherits the full permissions of the user who created it, so a regular user's token reaches only what that user can, and a site administrator's token can call admin-only operations such as creating, updating, and deleting users or adding an external service. The single optional scope, site-admin:sudo, only controls whether the token may impersonate other users; it does not narrow the token's reach. This is why a least-privilege layer in front of Sourcegraph matters: the token itself cannot be scoped down.
Should I use the GraphQL API or the Stream Search API for search?+
Sourcegraph recommends the Stream Search API at /.api/search/stream for production code search, because it returns matches over server-sent events as they are found, which is more responsive for large result sets. The GraphQL search query is documented as intended mainly for debugging and scripting and has no backwards-compatibility guarantee across releases, so it suits one-off queries and automation rather than a user-facing search experience.
Does Sourcegraph have an official MCP server?+
Yes. Sourcegraph publishes an official Model Context Protocol server that gives an AI agent cross-repository code intelligence. Core tools answer at /.api/mcp, the full tool suite at /.api/mcp/all, and Deep Search tools at /.api/mcp/deepsearch, exposing operations such as keyword_search, read_file, list_repos, go_to_definition, and find_references. It is an experimental feature on Enterprise plans, announced in September 2025, and authenticates with an access token or OAuth 2.0. Use of it requires the MCP#ACCESS permission on the user.
Is the GraphQL API versioned?+
No. The GraphQL schema has no dated version string. It ships with each Sourcegraph release and has no backwards-compatibility guarantee across releases, so the same operation can change between versions. An integration should track the schema of the Sourcegraph version its instance runs, and the API console on the instance shows the live schema for that release.
How are rate limits enforced?+
Sourcegraph limits GraphQL queries by cost rather than by a fixed request-per-minute quota. The per-instance ceilings cap query depth at 30, returned fields at 500,000, and aliases at 500 by default, and an administrator can change them in site configuration. A query that exceeds a ceiling is rejected with a GraphQL error rather than served. The stream search route bounds a single search through query parameters such as display and max-line-len instead.
Why did my query return data and errors at the same time?+
GraphQL returns a single HTTP 200 for a syntactically valid request, with any problems listed in an errors array in the response body alongside whatever data could be resolved. A request can therefore partially succeed: some fields resolve while others report a permission or lookup error. An integration should always read the errors array, not just the HTTP status, to know whether every field came back.
Related

More developer API guides for agents

What is Bollard AI?

Control what every AI agent can do in Sourcegraph.

Bollard AI sits between a team's AI agents and Sourcegraph. Grant each agent exactly the access it needs, read or write, area by area, and every call is checked and logged.

  • Set read, write, or full access per agent, never a shared Sourcegraph token.
  • Denied by default, so an agent reaches only what has been explicitly allowed.
  • Every call recorded in plain English: who, what, where, and the decision.
Sourcegraph
Code Search Agent
Search code ActionOffReadFull use
Read files and blobs ResourceOffReadFull use
Create batch changes ActionOffReadFull use
Manage users ResourceOffReadFull use
Per-agent access, set in Bollard AI, not in Sourcegraph