Skip to content

Context7 Platform -- Up-to-date docs for AI agents

13.0 KB
Raw Blame
import { access } from "fs/promises";
import { join } from "path";
import { homedir } from "os";

export type Transport = "http" | "stdio";

export type AuthOptions =
  { mode: "api-key"; apiKey: string } | { mode: "oauth" | "none"; apiKey?: never };
export type AuthMode = AuthOptions["mode"];

export const AUTH_MODE_LABELS: Record<AuthMode, string> = {
  oauth: "OAuth",
  "api-key": "API Key",
  none: "no authentication",
};

export const STDIO_PACKAGE = "@upstash/context7-mcp";

function stdioArgs(auth: AuthOptions): string[] {
  const args = ["-y", STDIO_PACKAGE];
  if (auth.mode === "api-key") {
    args.push("--api-key", auth.apiKey);
  }
  return args;
}

function stdioEntry(auth: AuthOptions): Record<string, unknown> {
  return { command: "npx", args: stdioArgs(auth) };
}

function claudeConfigDir(): string {
  return process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
}

function claudeGlobalMcpPath(): string {
  if (process.env.CLAUDE_CONFIG_DIR) {
    return join(claudeConfigDir(), ".claude.json");
  }
  return join(homedir(), ".claude.json");
}

export function resolveVscodeUserDir(
  platform: NodeJS.Platform = process.platform,
  home: string = homedir(),
  env: { APPDATA?: string; XDG_CONFIG_HOME?: string } = {
    APPDATA: process.env.APPDATA,
    XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
  }
): string {
  if (platform === "win32") {
    return join(env.APPDATA || join(home, "AppData", "Roaming"), "Code", "User");
  }
  if (platform === "darwin") {
    return join(home, "Library", "Application Support", "Code", "User");
  }
  return join(env.XDG_CONFIG_HOME || join(home, ".config"), "Code", "User");
}

export function resolveDevinConfigDir(
  platform: NodeJS.Platform = process.platform,
  home: string = homedir(),
  env: { APPDATA?: string } = { APPDATA: process.env.APPDATA }
): string {
  if (platform === "win32") {
    return join(env.APPDATA || join(home, "AppData", "Roaming"), "devin");
  }
  return join(home, ".config", "devin");
}

export type RuleType =
  | {
      kind: "file";
      dir: (scope: "project" | "global") => string;
      filename: string;
      contentPrefix?: string;
    }
  | { kind: "append"; file: (scope: "project" | "global") => string; sectionMarker: string };

export interface AgentConfig {
  displayName: string;
  setupDescription?: string;
  mcp: {
    projectPaths: string[];
    globalPaths: string[];
    configKey: string;
    buildEntry: (
      auth: AuthOptions,
      transport: Transport,
      mcpUrl: string
    ) => Record<string, unknown>;
  };
  rule: RuleType;
  skill: {
    name: string;
    dir: (scope: "project" | "global") => string;
  };
  detect: {
    projectPaths: string[];
    globalPaths: string[];
  };
}

/**
 * Attaches the API key as a standard `Authorization: Bearer` header.
 *
 * The name must stay `Authorization`. Codex resolves a server's auth mode from
 * `bearer_token_env_var` or a header literally named `Authorization`
 * (`auth_status_before_discovery` in codex-rs/rmcp-client/src/auth_status.rs);
 * any other name reads as "no credential configured", so it falls through to an
 * OAuth credential stored against the same server name and URL and refreshes it
 * at startup. A dead refresh token then fails the server before the key is ever
 * sent. The server accepts the legacy `CONTEXT7_API_KEY` header too, so existing
 * configs keep working.
 *
 */
function withHeaders(base: Record<string, unknown>, auth: AuthOptions): Record<string, unknown> {
  if (auth.mode === "api-key") {
    return { ...base, headers: { Authorization: `Bearer ${auth.apiKey}` } };
  }
  return base;
}

const agents = {
  claude: {
    displayName: "Claude Code",
    mcp: {
      projectPaths: [".mcp.json"],
      get globalPaths() {
        return [claudeGlobalMcpPath()];
      },
      configKey: "mcpServers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio" ? stdioEntry(auth) : withHeaders({ type: "http", url: mcpUrl }, auth),
    },
    rule: {
      kind: "file",
      dir: (scope) =>
        scope === "global" ? join(claudeConfigDir(), "rules") : join(".claude", "rules"),
      filename: "context7.md",
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(claudeConfigDir(), "skills") : join(".claude", "skills"),
    },
    detect: {
      projectPaths: [".mcp.json", ".claude"],
      get globalPaths() {
        return [claudeConfigDir()];
      },
    },
  },

  cursor: {
    displayName: "Cursor",
    mcp: {
      projectPaths: [join(".cursor", "mcp.json")],
      globalPaths: [join(homedir(), ".cursor", "mcp.json")],
      configKey: "mcpServers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio" ? stdioEntry(auth) : withHeaders({ url: mcpUrl }, auth),
    },
    rule: {
      kind: "file",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".cursor", "rules") : join(".cursor", "rules"),
      filename: "context7.mdc",
      contentPrefix: `---\nalwaysApply: true\n---\n\n`,
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".cursor", "skills") : join(".cursor", "skills"),
    },
    detect: {
      projectPaths: [".cursor"],
      globalPaths: [join(homedir(), ".cursor")],
    },
  },

  vscode: {
    displayName: "VS Code",
    mcp: {
      projectPaths: [join(".vscode", "mcp.json")],
      get globalPaths() {
        return [join(resolveVscodeUserDir(), "mcp.json")];
      },
      configKey: "servers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio"
          ? { type: "stdio", ...stdioEntry(auth) }
          : withHeaders({ type: "http", url: mcpUrl }, auth),
    },
    rule: {
      kind: "file",
      dir: (scope) =>
        scope === "global"
          ? join(resolveVscodeUserDir(), "prompts")
          : join(".github", "instructions"),
      filename: "context7.instructions.md",
      contentPrefix: `---\napplyTo: "**"\n---\n\n`,
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".agents", "skills") : join(".agents", "skills"),
    },
    detect: {
      projectPaths: [".vscode"],
      get globalPaths() {
        return [resolveVscodeUserDir()];
      },
    },
  },

  devin: {
    displayName: "Devin",
    mcp: {
      projectPaths: [join(".devin", "mcp_config.json")],
      get globalPaths() {
        return [join(resolveDevinConfigDir(), "mcp_config.json")];
      },
      configKey: "mcpServers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio"
          ? stdioEntry(auth)
          : withHeaders({ transport: "http", url: mcpUrl }, auth),
    },
    rule: {
      kind: "append",
      file: (scope) =>
        scope === "global" ? join(resolveDevinConfigDir(), "AGENTS.md") : "AGENTS.md",
      sectionMarker: "<!-- context7 -->",
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(resolveDevinConfigDir(), "skills") : join(".devin", "skills"),
    },
    detect: {
      projectPaths: [".devin"],
      get globalPaths() {
        return [resolveDevinConfigDir()];
      },
    },
  },

  copilot: {
    displayName: "GitHub Copilot CLI",
    mcp: {
      projectPaths: [".mcp.json"],
      globalPaths: [join(homedir(), ".copilot", "mcp-config.json")],
      configKey: "mcpServers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio"
          ? { type: "stdio", ...stdioEntry(auth), tools: ["*"] }
          : withHeaders({ type: "http", url: mcpUrl, tools: ["*"] }, auth),
    },
    rule: {
      kind: "append",
      file: (scope) =>
        scope === "global" ? join(homedir(), ".copilot", "AGENTS.md") : "AGENTS.md",
      sectionMarker: "<!-- context7 -->",
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".agents", "skills") : join(".agents", "skills"),
    },
    detect: {
      // Copilot shares .mcp.json with Claude Code, so project ownership cannot
      // be inferred safely. Project setup remains available via --copilot.
      projectPaths: [],
      globalPaths: [join(homedir(), ".copilot")],
    },
  },

  opencode: {
    displayName: "OpenCode",
    mcp: {
      projectPaths: ["opencode.json", "opencode.jsonc", ".opencode.json", ".opencode.jsonc"],
      globalPaths: [
        join(homedir(), ".config", "opencode", "opencode.json"),
        join(homedir(), ".config", "opencode", "opencode.jsonc"),
        join(homedir(), ".config", "opencode", ".opencode.json"),
        join(homedir(), ".config", "opencode", ".opencode.jsonc"),
      ],
      configKey: "mcp",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio"
          ? { type: "local", command: ["npx", ...stdioArgs(auth)], enabled: true }
          : withHeaders({ type: "remote", url: mcpUrl, enabled: true }, auth),
    },
    rule: {
      kind: "append",
      file: (scope) =>
        scope === "global" ? join(homedir(), ".config", "opencode", "AGENTS.md") : "AGENTS.md",
      sectionMarker: "<!-- context7 -->",
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".agents", "skills") : join(".agents", "skills"),
    },
    detect: {
      projectPaths: ["opencode.json", "opencode.jsonc", ".opencode.json", ".opencode.jsonc"],
      globalPaths: [join(homedir(), ".config", "opencode")],
    },
  },

  codex: {
    displayName: "Codex",
    mcp: {
      projectPaths: [join(".codex", "config.toml")],
      globalPaths: [join(homedir(), ".codex", "config.toml")],
      configKey: "mcp_servers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio" ? stdioEntry(auth) : withHeaders({ type: "http", url: mcpUrl }, auth),
    },
    rule: {
      kind: "append",
      file: (scope) => (scope === "global" ? join(homedir(), ".codex", "AGENTS.md") : "AGENTS.md"),
      sectionMarker: "<!-- context7 -->",
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".agents", "skills") : join(".agents", "skills"),
    },
    detect: {
      projectPaths: [".codex"],
      globalPaths: [join(homedir(), ".codex")],
    },
  },

  // Antigravity is built on Gemini infrastructure and shares ~/.gemini/. Per
  // the official Codelabs guide, Antigravity 2.0/IDE/CLI read MCP servers from
  // ~/.gemini/config/mcp_config.json globally; there is no project-level MCP
  // config, so projectPaths is empty and setupAgent falls back to global.
  antigravity: {
    displayName: "Antigravity",
    setupDescription: "Set up for Antigravity (.agent/skills)",
    mcp: {
      projectPaths: [],
      globalPaths: [join(homedir(), ".gemini", "config", "mcp_config.json")],
      configKey: "mcpServers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio" ? stdioEntry(auth) : withHeaders({ serverUrl: mcpUrl }, auth),
    },
    rule: {
      kind: "append",
      file: (scope) => (scope === "global" ? join(homedir(), ".gemini", "GEMINI.md") : "GEMINI.md"),
      sectionMarker: "<!-- context7 -->",
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".agent", "skills") : join(".agent", "skills"),
    },
    detect: {
      projectPaths: [".agent"],
      globalPaths: [join(homedir(), ".gemini", "antigravity"), join(homedir(), ".agent")],
    },
  },

  gemini: {
    displayName: "Gemini CLI",
    mcp: {
      projectPaths: [join(".gemini", "settings.json")],
      globalPaths: [join(homedir(), ".gemini", "settings.json")],
      configKey: "mcpServers",
      buildEntry: (auth, transport, mcpUrl) =>
        transport === "stdio" ? stdioEntry(auth) : withHeaders({ httpUrl: mcpUrl }, auth),
    },
    rule: {
      kind: "append",
      file: (scope) => (scope === "global" ? join(homedir(), ".gemini", "GEMINI.md") : "GEMINI.md"),
      sectionMarker: "<!-- context7 -->",
    },
    skill: {
      name: "context7-mcp",
      dir: (scope) =>
        scope === "global" ? join(homedir(), ".gemini", "skills") : join(".gemini", "skills"),
    },
    detect: {
      projectPaths: [".gemini"],
      globalPaths: [join(homedir(), ".gemini")],
    },
  },
} satisfies Record<string, AgentConfig>;

export type SetupAgent = keyof typeof agents;

export function getAgent(name: SetupAgent): AgentConfig {
  return agents[name];
}

export const ALL_AGENT_NAMES: SetupAgent[] = Object.keys(agents) as SetupAgent[];

async function pathExists(p: string): Promise<boolean> {
  try {
    await access(p);
    return true;
  } catch {
    return false;
  }
}

export async function detectAgents(scope: "project" | "global"): Promise<SetupAgent[]> {
  const detected: SetupAgent[] = [];

  for (const name of ALL_AGENT_NAMES) {
    const agent = agents[name];
    const paths = scope === "global" ? agent.detect.globalPaths : agent.detect.projectPaths;
    for (const p of paths) {
      const fullPath = scope === "global" ? p : join(process.cwd(), p);
      if (await pathExists(fullPath)) {
        detected.push(name);
        break;
      }
    }
  }

  return detected;
}