A reference guide for building AI agents: every method, how to authenticate, and the permissions each one needs.
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.
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.
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.
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.
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.
An access token is created under Settings then Access tokens and sent as 'Authorization: token
An OAuth app issues a user token with the user:all scope, sent as 'Authorization: Bearer
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="
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.
Search code across every connected repository through GraphQL, and stream the same search over server-sent events as matches are found.
Look up a single repository by name and list the repositories on an instance.
Read a file's content and metadata at a given revision through the gitBlob field on a repository commit.
Read the current user, look up a user or an organization, and run admin-only operations to create, update, and delete users.
Create batch changes, build and execute a batch spec, and apply a change set across many repositories at once.
List code insight views and create a saved search context that scopes future searches to chosen repositories.
Connect a code host as an external service so its repositories are mirrored and searchable.
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.
| Method | Endpoint | What it does | Access | Permission | Version | |
|---|---|---|---|---|---|---|
Code searchSearch code across every connected repository through GraphQL, and stream the same search over server-sent events as matches are found.2 | ||||||
| POST | query search(query: String!) | Run a code search across connected repositories and return the matching results. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| GET | /.api/search/stream | Run a search and receive matches, progress, filters, and a final done event over server-sent events as they are found. | read | — | Current | |
Requires a token with the user:all scope, sent as 'Authorization: token Acts onsearch result Permission (capability)None required VersionAvailable since the API’s base version Webhook eventNone Rate limitStandard limits apply SourceOfficial documentation ↗ | ||||||
RepositoriesLook up a single repository by name and list the repositories on an instance.2 | ||||||
| POST | query repository(name: String!) | Look up a single repository by its name, such as github.com/org/repo. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | query repositories(first: Int, query: String) | List the repositories on an instance, with optional paging and a name filter. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
Files & blobsRead a file's content and metadata at a given revision through the gitBlob field on a repository commit.1 | ||||||
| POST | query repository.commit.blob(path: String!) | Read a file's content and metadata at a given revision through the gitBlob field on a repository commit. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
Users & organizationsRead the current user, look up a user or an organization, and run admin-only operations to create, update, and delete users.6 | ||||||
| POST | query currentUser | Read the user the access token belongs to, such as the username. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | query user(username: String) | Look up a single user by username. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | mutation createUser(username: String!, email: String) | Create a new user, returning the user and a password-reset URL. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | mutation updateUser(user: ID!) | Update a user's metadata, such as username and account details. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | mutation deleteUser(user: ID!, hard: Boolean) | Delete a user; with hard set to true the user and all associated data are removed permanently. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | query organization(name: String!) | Look up an organization by name. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
Batch changesCreate batch changes, build and execute a batch spec, and apply a change set across many repositories at once.4 | ||||||
| POST | mutation createEmptyBatchChange(namespace: ID!, name: String!) | Create an empty batch change in a namespace, ready to attach a batch spec. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | mutation createBatchSpecFromRaw(batchSpec: String!, namespace: ID!) | Create a batch spec from raw input, defining the change to run across repositories. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | mutation executeBatchSpec(batchSpec: ID!) | Execute a batch spec by its ID, producing the change sets it describes. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | mutation applyBatchChange(batchSpec: ID!) | Apply a batch spec to create or update a batch change, opening or updating pull requests across repositories. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
Code insights & contextsList code insight views and create a saved search context that scopes future searches to chosen repositories.2 | ||||||
| POST | query insightViews | List the code insight views the token's user can see, with optional cursor paging and repository filtering. | read | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
| POST | mutation createSearchContext(searchContext: SearchContextInput!) | Create a saved search context that scopes future searches to a chosen set of repositories and revisions. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
AdministrationConnect a code host as an external service so its repositories are mirrored and searchable.1 | ||||||
| POST | mutation addExternalService(input: AddExternalServiceInput!) | Connect a code host as an external service so its repositories are mirrored and searchable. | write | — | Current | |
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 SourceOfficial documentation ↗ | ||||||
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.
| Event | What it signals | Triggered by |
|---|
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.
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.
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.
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.
The status codes an agent should handle, and what to do about each.
| Status | Code | Meaning | What to do |
|---|---|---|---|
| 200 | GraphQL errors array | A 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. |
| 401 | Unauthorized | The 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. |
| 403 | Forbidden | The 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. |
| 400 | Bad Request | The 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. |
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.
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.
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.
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.
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.
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 ↗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.