Skip to content

Connecting ​

Every Source Graph instance serves four entry points under the /sourcegraph/ path of its origin. Pick the one that fits the caller; all of them run the same operations with the same rules.

CallerEntry point
A personThe website at /sourcegraph/ — search, code reading, repositories and the Connect page
An AI Agent or MCP client/sourcegraph/mcp — Streamable HTTP, stateless, JSON responses
A script or serviceThe HTTP API — /sourcegraph/v1/… for repository reads and /sourcegraph/api/search for search
A terminalsourcegraph-cli, a small HTTP client for the same routes

The website's Connect page always shows ready-to-copy configuration for the instance you are on, including the right address and whether a token is needed. Prefer it over hand-written examples when they differ.

Source Graph is optional ​

Context does not require Source Graph. If you never install or configure it, Context's query skill still reads code evidence by itself: it makes a shallow, sparse partial clone of the recorded commit and searches it with grep or rg. In the default auto mode the skill prefers Source Graph only when an authorized instance is available, so connect one when you want pinned remote reads without local checkouts.

To try it without deploying anything, use the public demo at https://context4ai-portal.fly.dev/sourcegraph/; its MCP endpoint is /sourcegraph/mcp.

Choose a credential ​

CredentialHow to get itWhat it allows
None (anonymous)—Read-only access to repositories marked public, when the site allows public reading; rate-limited per client
Personal API key (sgk_…)Sign in, open your user settings and create an API tokenThe same reads as your account, over HTTP or MCP. Administrators can create keys that may also request indexing over MCP
Service tokenThe SOURCEGRAPH_API_TOKEN setting of the instance, at least 32 charactersEvery HTTP and MCP operation, including registration and indexing — for automation you control

Send keys and tokens as Authorization: Bearer <value>. An invalid credential is rejected with AUTHENTICATION_REQUIRED; it never falls back to anonymous access. Keep credentials in your client's secret store or environment, never in shared configuration files. Authentication and Access Control explains each mode in detail.

Connect an MCP client ​

Point any client that supports Streamable HTTP at the /mcp endpoint. For the public demo:

json
{
  "mcpServers": {
    "context-sourcegraph": {
      "type": "http",
      "url": "https://context4ai.org/sourcegraph/mcp?plugins=auto"
    }
  }
}

For an instance that needs a credential, add "headers": { "Authorization": "Bearer <token>" }. The Connect page also shows the equivalent command or file for Claude Code, Codex and Cursor. Naming the server context-sourcegraph lets Context's query Skill find it, as described in Reading Code Evidence Remotely.

The optional plugins query parameter controls repository plugins for the whole connection: auto (default selection), off, or up to 16 comma-separated plugin names. Anonymous connections and personal keys get the read-only tools; prepare appears only for the service token and for administrator keys allowed to prepare. Use MCP tool discovery for the current input schemas — the HTTP and MCP reference lists them.

Call the HTTP API ​

Every repository-specific request names the repository with the repo query parameter, as owner/repository. Request bodies are JSON objects with capitalized field names; unknown fields are rejected.

bash
# Search at the default branch head
curl -s -X POST 'https://context4ai.org/sourcegraph/api/search?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Pattern":"timeout","IgnoreCase":true,"Paths":["packages"]}'

# Read lines at the commit returned in Meta.Commit
curl -s -X POST 'https://context4ai.org/sourcegraph/v1/repo/read?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Revision":"<commit>","Path":"README.md","StartLine":1,"EndLine":40}'

read_many is available only over MCP; over HTTP, issue several read calls.

Use the command-line client ​

sourcegraph-cli is built with the service and reads two environment variables: SOURCEGRAPH_URL, the instance's /sourcegraph base address (default https://context4ai.org/sourcegraph, and it must be HTTPS), and the optional SOURCEGRAPH_API_TOKEN. Search flags follow rg:

bash
export SOURCEGRAPH_URL="https://context4ai.org/sourcegraph"
sourcegraph-cli search -repo context4ai/context -g '*.ts' 'OnboardingVersion' packages
sourcegraph-cli read -repo context4ai/context -revision <commit> \
  -path README.md -start-line 1 -end-line 40

It prints the raw JSON response and exits with 3 when a request is accepted but not ready yet. All commands and flags are in the CLI reference.

The search-then-read loop ​

Agents get the most from Source Graph with a short loop:

  1. Search the repository. Omit the revision to use its default branch head, or pass a monitored branch or a full commit you already know.
  2. Pin the commit returned in the result's metadata.
  3. Read the decisive ranges at that commit — directly when the file is known, several at once with read_many.
  4. Continue from the returned next line if the file goes on, and treat Partial, Truncated and coverage flags as limits, not as proof that something is absent.

There is no need to list repositories or resolve the revision before every query; do that only when the repository is unknown or a request fails. A 409 INDEX_NOT_READY means that commit has not been indexed yet — see Operations for what to do.

接入 ​

每个 Source Graph 实例都在其源站的 /sourcegraph/ 路径下提供四个入口。按调用方选择合适的入口即可;它们执行相同的操作,遵循相同的规则。

调用方入口
人位于 /sourcegraph/ 的网站:搜索、代码阅读、仓库以及 Connect(接入)页面
AI Agent 或 MCP 客户端/sourcegraph/mcp:Streamable HTTP,无状态,返回 JSON
脚本或服务HTTP API:仓库读取使用 /sourcegraph/v1/…,搜索使用 /sourcegraph/api/search
终端sourcegraph-cli,一个调用相同路由的小型 HTTP 客户端

网站的 Connect 页面始终会展示当前实例可直接复制的配置,包括正确的地址以及是否需要令牌。当它与手写示例不一致时,以该页面为准。

Source Graph 是可选的 ​

Context 并不依赖 Source Graph。即使从未安装或配置它,Context 的查询技能也能自行读取代码证据:对记录的提交做浅层、稀疏的部分克隆,再用 grep 或 rg 搜索。默认的 auto 模式只在有可用的已授权实例时才优先使用 Source Graph,因此当你希望按固定版本远程读取、又不想在本地检出代码时,再接入它。

想不部署就试用,可以直接使用公开示例 https://context4ai-portal.fly.dev/sourcegraph/,其 MCP 端点为 /sourcegraph/mcp。

选择凭据 ​

凭据获取方式允许的操作
无(匿名)—当站点允许公开读取时,只读访问标记为公开的仓库;按客户端限流
个人 API Key(sgk_…)登录后打开用户设置,创建 API 令牌通过 HTTP 或 MCP 执行与你的账号相同的读取操作。管理员创建的 Key 还可以通过 MCP 请求建索引
服务令牌实例的 SOURCEGRAPH_API_TOKEN 设置,至少 32 个字符所有 HTTP 和 MCP 操作,包括登记和建索引,适用于你自己掌控的自动化流程

以 Authorization: Bearer <value> 的形式发送 Key 和令牌。无效凭据会被拒绝并返回 AUTHENTICATION_REQUIRED,绝不会回退为匿名访问。请将凭据保存在客户端的密钥存储或环境变量中,不要放进共享的配置文件。各模式的详细说明见登录与准入。

接入 MCP 客户端 ​

将任何支持 Streamable HTTP 的客户端指向 /mcp 端点。公开演示实例的配置如下:

json
{
  "mcpServers": {
    "context-sourcegraph": {
      "type": "http",
      "url": "https://context4ai.org/sourcegraph/mcp?plugins=auto"
    }
  }
}

如果实例需要凭据,添加 "headers": { "Authorization": "Bearer <token>" }。Connect 页面还会展示 Claude Code、Codex 和 Cursor 对应的命令或配置文件。将服务器命名为 context-sourcegraph,Context 的查询 Skill 就能找到它,详见远程读取代码证据。

可选的 plugins 查询参数控制整个连接使用的仓库插件:auto(默认选择)、off,或最多 16 个以逗号分隔的插件名称。匿名连接和个人 Key 只能获得只读工具;prepare 只对服务令牌以及被允许执行准备的管理员 Key 可见。当前的输入 schema 请通过 MCP 工具发现获取,HTTP 与 MCP 接口参考文档中列出了这些工具。

调用 HTTP API ​

每个针对具体仓库的请求都通过 repo 查询参数指定仓库,格式为 owner/repository。请求体是字段名首字母大写的 JSON 对象,未知字段会被拒绝。

bash
# Search at the default branch head
curl -s -X POST 'https://context4ai.org/sourcegraph/api/search?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Pattern":"timeout","IgnoreCase":true,"Paths":["packages"]}'

# Read lines at the commit returned in Meta.Commit
curl -s -X POST 'https://context4ai.org/sourcegraph/v1/repo/read?repo=context4ai/context' \
  -H 'Content-Type: application/json' \
  -d '{"Revision":"<commit>","Path":"README.md","StartLine":1,"EndLine":40}'

read_many 只能通过 MCP 使用;通过 HTTP 时,请发起多次 read 调用。

使用命令行客户端 ​

sourcegraph-cli 随服务一同构建,读取两个环境变量:SOURCEGRAPH_URL 是实例的 /sourcegraph 基础地址(默认 https://context4ai.org/sourcegraph,必须是 HTTPS);SOURCEGRAPH_API_TOKEN 可选。搜索参数沿用 rg 的风格:

bash
export SOURCEGRAPH_URL="https://context4ai.org/sourcegraph"
sourcegraph-cli search -repo context4ai/context -g '*.ts' 'OnboardingVersion' packages
sourcegraph-cli read -repo context4ai/context -revision <commit> \
  -path README.md -start-line 1 -end-line 40

它会输出原始 JSON 响应;当请求已被接受但尚未就绪时,以 3 退出。所有命令和参数见 CLI 参考文档。

先搜索、再读取的循环 ​

Agent 用一个简短的循环就能充分利用 Source Graph:

  1. 搜索仓库。省略 revision 时使用默认分支的最新提交,也可以传入监控分支或已知的完整提交。
  2. 固定提交:记下结果元数据中返回的提交。
  3. 在该提交上读取关键范围:已知文件时直接读取,需要多处时用 read_many 一次读取。
  4. 如果文件还有后续内容,从返回的下一行继续读取;将 Partial、Truncated 和覆盖范围标记视为限制,而不是内容不存在的证明。

无需在每次查询前都列出仓库或解析 revision;只有在仓库未知或请求失败时才这样做。409 INDEX_NOT_READY 表示该提交尚未建好索引,处理方法见运维。