Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
13 changes: 13 additions & 0 deletions .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "context4ai-sourcegraph",
"owner": {
"name": "context4ai"
},
"plugins": [
{
"name": "sourcegraph",
"source": "./",
"description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI."
}
]
}
12 changes: 12 additions & 0 deletions .claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "sourcegraph",
"description": "Search and read code in a Sourcegraph service at pinned commits, and register or maintain its repositories, through MCP or the sourcegraph CLI.",
"version": "0.5.0",
"author": {
"name": "context4ai"
},
"license": "MIT",
"homepage": "https://github.com/context4ai/sourcegraph",
"keywords": ["sourcegraph", "code-search", "mcp", "agent-skill"],
"skills": ["./skills/sourcegraph"]
}
47 changes: 47 additions & 0 deletions .github/workflows/cli-release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Release CLI
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: Existing release tag to attach the CLI to
required: true
type: string
permissions:
contents: write
jobs:
cli:
runs-on: ubuntu-latest
env:
TAG: ${{ inputs.tag || github.event.release.tag_name }}
steps:
- uses: actions/checkout@v7
with:
ref: ${{ env.TAG }}
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.9
- uses: actions/setup-node@v6
with:
node-version: 24
registry-url: https://registry.npmjs.org
- name: Build and pack
working-directory: cli
run: |
bun install --frozen-lockfile
bun run build
node dist/sourcegraph.js --version
npm pack
mv c4a-sourcegraph-*.tgz sourcegraph-cli.tgz
# The stable address releases/latest/download/sourcegraph-cli.tgz installs the newest CLI.
- name: Attach to the release
env:
GH_TOKEN: ${{ github.token }}
run: gh release upload "$TAG" cli/sourcegraph-cli.tgz --clobber
- name: Publish to npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
if: env.NODE_AUTH_TOKEN != ''
working-directory: cli
run: npm publish --access public
3 changes: 2 additions & 1 deletion DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ CI runs the same verification on pull requests and `main`; see `.github/workflow
| Environment variable | Default / purpose |
| --- | --- |
| `SOURCEGRAPH_DATABASE` | `sqlite`; also `postgres` or `mongodb` |
| `DATABASE_URL` | SQLite absolute file path (default `/data/sourcegraph.db`), PostgreSQL DSN, or standard MongoDB URI |
| `DATABASE_URL` | SQLite absolute file path (default `/data/sourcegraph.db`), PostgreSQL DSN, or standard MongoDB URI (`mongodb://` or `mongodb+srv://`; the path names the database, default `c4a`) |
| `SOURCEGRAPH_DATA_ROOT` | `/data`; persistent Git, indexes and manifests |
| `SOURCEGRAPH_ORIGIN` | `http://localhost:8080`; public origin, without a path |
| `SOURCEGRAPH_LISTEN` | `0.0.0.0:8080` |
Expand All @@ -43,6 +43,7 @@ CI runs the same verification on pull requests and `main`; see `.github/workflow
| `SOURCEGRAPH_API_TOKEN` | First-start seed for the database-backed service bearer, at least 32 characters; generated if absent |
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | Google web OAuth client, imported together into the database on first configuration |
| `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | GitHub OAuth app, imported together into the database on first configuration |
| `SOURCEGRAPH_GIT_READER_POOL` | Set `off` to read files with one Git command per read instead of long-lived `git cat-file` processes (the processes are also skipped when the installed Git lacks `cat-file --batch-command -Z` with `%(objectmode)`) |

Repository read plugins are tuned with `SOURCEGRAPH_PLUGINS_*`; see [repository plugins](docs/ref/repository-plugins.md). The CLI reads `SOURCEGRAPH_URL` and `SOURCEGRAPH_API_TOKEN`; see [interfaces](docs/interfaces.md#cli).

Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ It is built for the workload AI coding agents generate: many small, precise `sea
- **Agent-ready.** A stateless Streamable HTTP MCP endpoint works with any MCP client; anonymous access is read-only and limited to public repositories.
- **Snapshot retention.** Shallow branch-head synchronization, on-demand pinned SHAs and per-repository storage budgets; see [snapshot configuration](docs/snapshots.md).
- **Small footprint.** One process manages Git mirrors, the Zoekt child process and background indexing. SQLite by default; PostgreSQL and MongoDB are supported.
- **Search without waiting for an index.** A commit that has no index yet is still searched — from the nearest index plus the files changed since, or by scanning its files — and the answer says so (`Meta.Hybrid`, `Meta.Unindexed`).
- **Checkout-free knowledge updates.** Metadata-only diffs, raw blobs (one or a batch), recursive directory listings and an availability check for a commit and paths let tools such as [Context](https://github.com/context4ai/context) update knowledge without cloning; see [remote reads](docs/interfaces.md#remote-reads).
- **Tags, token scopes and manual updates.** Label repositories with tags, narrow personal tokens to tagged or non-public repositories, and register repositories that update only on request.
- **Extensible reads.** Repositories can ship Wasm plugins (`<name>.sourcegraph.wasm`) that change how `read` and `read_many` present files. See [repository plugins](docs/ref/repository-plugins.md).

## Performance
Expand Down Expand Up @@ -61,6 +64,16 @@ curl -s -X POST 'https://context4ai.org/sourcegraph/api/search?repo=context4ai/c
-d '{"Pattern":"TODO","FixedStrings":true}'
```

Or use the CLI and the agent skill:

```sh
npm i -g https://github.com/context4ai/sourcegraph/releases/latest/download/sourcegraph-cli.tgz
sourcegraph search -r context4ai/sourcegraph -g '*.go' 'func main'
npx skills add context4ai/sourcegraph --skill sourcegraph # Claude Code, Codex, Cursor and others
```

In Claude Code the repository is also a plugin marketplace: `/plugin install sourcegraph --marketplace context4ai/sourcegraph`.

The site's **Connect** page always shows current HTTP and client examples. See [interfaces](docs/interfaces.md) for MCP, HTTP and CLI details.

## Run your own
Expand Down
13 changes: 13 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ Context Source Graph 是一个可自托管的代码搜索服务,基于 Go、Gi
- **一套契约,四种入口。** 浏览器、HTTP、MCP 与 CLI 共享相同的操作:`repositories`、`availability`、`resolve`、`search`、`read`、`list`、`diff` 和 `prepare`;MCP 另有 `read_many`,一次调用读取多处。详见[接口](docs/interfaces.md)。
- **为 Agent 而生。** 无状态的 Streamable HTTP MCP 端点可接入任意 MCP 客户端;匿名访问只读,且仅限公开仓库。
- **轻量。** 单个进程即可管理 Git 镜像、Zoekt 子进程和后台索引。默认使用 SQLite,同时支持 PostgreSQL 与 MongoDB。
- **无需等待索引也能搜索。** 还没有索引的提交同样可以搜索:用最近的索引加上之后变化的文件作答,或直接扫描它的文件,并在结果中标明(`Meta.Hybrid`、`Meta.Unindexed`)。
- **免克隆更新知识。** 仅元数据的差异、原始文件读取(单个或批量)、递归目录列表,以及按提交和路径查询可读状态,让 [Context](https://github.com/context4ai/context) 等工具无需克隆即可更新知识,详见[远程读取](docs/interfaces.md#remote-reads)。
- **标签、Token 范围与手动更新。** 用标签标记仓库,把个人 Token 限定到带某些标签或非公开的仓库,并可登记只在需要时更新的仓库。
- **可扩展的读取。** 仓库可以自带 Wasm 插件(`<name>.sourcegraph.wasm`),定制 `read` 与 `read_many` 的文件呈现方式,详见[仓库插件](docs/ref/repository-plugins.md)。

## 性能
Expand Down Expand Up @@ -60,6 +63,16 @@ curl -s -X POST 'https://context4ai.org/sourcegraph/api/search?repo=context4ai/c
-d '{"Pattern":"TODO","FixedStrings":true}'
```

也可以使用 CLI 和 Agent Skill:

```sh
npm i -g https://github.com/context4ai/sourcegraph/releases/latest/download/sourcegraph-cli.tgz
sourcegraph search -r context4ai/sourcegraph -g '*.go' 'func main'
npx skills add context4ai/sourcegraph --skill sourcegraph # Claude Code、Codex、Cursor 等
```

在 Claude Code 中,这个仓库也是插件市场:`/plugin install sourcegraph --marketplace context4ai/sourcegraph`。

站点的 **Connect** 页面始终展示最新的 HTTP 与客户端示例。MCP、HTTP、CLI 的细节见[接口文档](docs/interfaces.md)。

## 自行部署
Expand Down
3 changes: 3 additions & 0 deletions cli/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
dist/
.tmp-config/
46 changes: 46 additions & 0 deletions cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# @c4a/sourcegraph

Command-line client for [Sourcegraph](https://github.com/context4ai/sourcegraph): search and read code at a pinned commit, register and manage repositories, and change personal and site settings. It uses the site's HTTP API, so it can do what the website does, with the same permissions.

```bash
npm i -g https://github.com/context4ai/sourcegraph/releases/latest/download/sourcegraph-cli.tgz
sourcegraph login # approve in the browser; a 90-day token is saved
sourcegraph search -r context4ai/sourcegraph -g '*.go' 'func main'
```

## Sites

| Site | Address |
| --- | --- |
| Context4AI (default) | https://context4ai.org/sourcegraph |

Choose with `--site default`, `--url <address>` (any https address, e.g. https://context4ai.org/sourcegraph), `SOURCEGRAPH_URL`, or `sourcegraph config set site <default|url>`. Sign-ins are kept per site.

## Sign-in

- `sourcegraph login` opens the site; after you approve, the CLI receives a personal API token (90 days) and stores it in `~/.config/sourcegraph/config.json` (mode 0600).
- `sourcegraph login --token sgk_…` stores a token created in User settings.
- `SOURCEGRAPH_API_TOKEN` overrides the stored token (CI, agents).
- `sourcegraph logout` revokes the token on the site and forgets it.

A token acts as its owner: it reads what you can read, manages repositories you manage, and — while you are a site administrator — administers the site.

## Commands

| Area | Commands |
| --- | --- |
| Query | `repos`, `search`, `read`, `read-many`, `list`, `diff`, `resolve`, `refs`, `status` |
| Repositories | `repo add/show/set/enable/disable/delete/purge/resume/managers` |
| Jobs | `jobs <repo> [list|cancel|sync|retry|index]` |
| Personal settings | `tokens [create|scope|delete]`, `credentials` |
| Tags | `tags`, `tags rename <old> <new>` |
| Site administration | `admin settings/users/role/credentials/query-errors/clear-jobs/cluster/instances/statistics/logs` |
| MCP | `mcp` prints a client configuration |

`sourcegraph admin logs [--hours N] [--level warn|error|info] [--msg TEXT] [--limit N]` shows service logs of all instances (default: warnings and errors, last 24 hours).

Run `sourcegraph <command> --help` for flags. `--json` prints the API's raw output; `--yes` skips confirmations.

Repository settings use `key=value` (`sourcegraph repo set org/repo sync_interval_minutes=60 public_read=false`). Intervals under 30 minutes are for site administrators; others are raised to 30 minutes with a warning. `manual_updates=true` turns off automatic updates (scheduled checks); `tags=a,b` replaces the tags and `tags=` clears them.

`sourcegraph repo add <repo> [--tag T]... [--manual]` labels a new repository and optionally registers it without automatic updates. `sourcegraph repos --tag T` lists repositories with any of the given tags.
20 changes: 20 additions & 0 deletions cli/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 30 additions & 0 deletions cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "@c4a/sourcegraph",
"version": "0.5.0",
"description": "Command-line client for Sourcegraph: search and read code at pinned commits, register and manage repositories, personal and site settings.",
"license": "MIT",
"type": "module",
"bin": {
"sourcegraph": "dist/sourcegraph.js"
},
"files": ["dist", "README.md"],
"repository": {
"type": "git",
"url": "git+https://github.com/context4ai/sourcegraph.git",
"directory": "cli"
},
"engines": {
"node": ">=18.3"
},
"scripts": {
"build": "node ../scripts/sync-deployment.mjs && bun build src/main.ts --target node --outfile dist/sourcegraph.js && node -e \"const f='dist/sourcegraph.js',fs=require('fs');const s=fs.readFileSync(f,'utf8');fs.writeFileSync(f,(s.startsWith('#!')?'':'#!/usr/bin/env node\\n')+s);fs.chmodSync(f,0o755)\"",
"test": "bun test"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/"
},
"devDependencies": {
"@types/node": "20",
"typescript": "5"
}
}
51 changes: 51 additions & 0 deletions cli/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { randomBytes } from 'node:crypto';

// One HTTP API request; errors carry the server's code and message.
export class ApiError extends Error {
constructor(public status: number, public code: string, message: string, public body: any) { super(message); }
}

export interface Request {
method?: string;
query?: Record<string, string | number | boolean | undefined>;
body?: unknown;
headers?: Record<string, string>;
anonymous?: boolean;
}

export class Client {
constructor(public site: string, public token?: string) {}

url(path: string, query?: Request['query']): string {
const u = new URL(this.site + path);
for (const [k, v] of Object.entries(query || {})) if (v !== undefined && v !== '') u.searchParams.set(k, String(v));
return u.toString();
}

async call<T = any>(path: string, req: Request = {}): Promise<T> {
const headers: Record<string, string> = { Accept: 'application/json', 'User-Agent': 'sourcegraph-cli', ...(req.headers || {}) };
if (this.token && !req.anonymous) headers.Authorization = 'Bearer ' + this.token;
if (req.body !== undefined) headers['Content-Type'] = 'application/json';
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 60_000);
let res: Response;
try {
res = await fetch(this.url(path, req.query), { method: req.method || (req.body !== undefined ? 'POST' : 'GET'), headers, body: req.body === undefined ? undefined : JSON.stringify(req.body), signal: ctl.signal, redirect: 'manual' });
} catch (e: any) {
throw new ApiError(0, 'NETWORK_ERROR', `Cannot reach ${this.site}: ${e?.cause?.code || e?.message || e}`, null);
} finally { clearTimeout(timer); }
const text = await res.text();
let body: any = text;
try { body = text ? JSON.parse(text) : {}; } catch { /* keep text */ }
if (!res.ok) {
const code = body?.Meta?.Code || body?.error || `HTTP_${res.status}`;
const message = body?.Error || body?.message || (typeof body === 'string' && body.slice(0, 200)) || code;
throw new ApiError(res.status, code, message, body);
}
return body as T;
}
}

export function idempotencyKey(): string {
return 'cli-' + randomBytes(12).toString('hex');
}
70 changes: 70 additions & 0 deletions cli/src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Site selection and the stored sign-in, one token per site.
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, dirname } from 'node:path';

import deployment from '../../config/deployment.json' with { type: 'json' };

// The sites come from the deployment profile (config/deployment.json), bundled
// at build time: a private deployment builds a CLI that knows its own sites.
export interface Site { id: string; label: string; url: string; aliases?: string[]; cli?: string }
export const DEPLOYMENT = deployment as unknown as {
sites: Site[]; default_site: string; site_aliases?: Record<string, string>; public_url?: string;
site_notice?: { site: string; recommend: string; cli?: string };
mcp_server_name?: string;
};
const trim = (u: string) => u.replace(/\/+$/, '');
export const SITES: Record<string, string> = Object.fromEntries(DEPLOYMENT.sites.map(s => [s.id, trim(s.url)]));
const ALIASES: Record<string, string> = DEPLOYMENT.site_aliases || {};
export const DEFAULT_SITE = SITES[DEPLOYMENT.default_site] || trim(DEPLOYMENT.sites[0].url);
const SITE_IDS = DEPLOYMENT.sites.map(s => s.id);

export interface Config { site?: string; tokens?: Record<string, string> }

export function configPath(): string {
const base = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
return join(base, 'sourcegraph', 'config.json');
}

export function loadConfig(): Config {
try { return JSON.parse(readFileSync(configPath(), 'utf8')) as Config; } catch { return {}; }
}

export function saveConfig(c: Config): void {
const p = configPath();
mkdirSync(dirname(p), { recursive: true, mode: 0o700 });
writeFileSync(p, JSON.stringify(c, null, 2) + '\n', { mode: 0o600 });
chmodSync(p, 0o600);
}

// A site is a site id (or an alias of one) of the deployment, or an https URL.
export function normalizeSite(value: string): string {
const v = value.trim();
const name = ALIASES[v.toLowerCase()] ?? v.toLowerCase();
if (SITES[name]) return SITES[name];
let u: URL;
try { u = new URL(v); } catch { throw new Error(`Unknown site "${value}": use ${SITE_IDS.join(', ')} or an https:// address`); }
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname))) throw new Error('The site address must use https://');
if (u.username || u.password || u.search || u.hash) throw new Error('The site address must not contain credentials, a query or a fragment');
return (u.origin + u.pathname).replace(/\/+$/, '');
}

export function siteName(url: string): string {
for (const [k, v] of Object.entries(SITES)) if (v === url) return k;
for (const s of DEPLOYMENT.sites) if ((s.aliases || []).map(trim).includes(url)) return s.id;
return url;
}

// --site/--url, then SOURCEGRAPH_URL, then the saved site, then the default site.
export function resolveSite(flag: string | undefined): string {
if (flag) return normalizeSite(flag);
if (process.env.SOURCEGRAPH_URL) return normalizeSite(process.env.SOURCEGRAPH_URL);
const saved = loadConfig().site;
return saved ? normalizeSite(saved) : DEFAULT_SITE;
}

// SOURCEGRAPH_API_TOKEN, then the token saved for this site.
export function resolveToken(site: string): string | undefined {
if (process.env.SOURCEGRAPH_API_TOKEN) return process.env.SOURCEGRAPH_API_TOKEN;
return loadConfig().tokens?.[site];
}
Loading