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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions src/adapters/axiosAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Adapter, AdapterResponse } from "../adapter";
import { AdapterError } from "../adapter";
import { ClientOptions } from "../clientOptions";
import { createRequestHeaders } from "./createRequestHeaders";
import { createUserAgent } from "./createUserAgent";

export class AxiosAdapter<TResource> implements Adapter<TResource> {
public async execute(options: ClientOptions): Promise<AdapterResponse<TResource>> {
Expand All @@ -21,11 +22,7 @@ export class AxiosAdapter<TResource> implements Adapter<TResource> {
};
if (typeof XMLHttpRequest === "undefined") {
if (config.headers) {
let userAgent = "ts-octopusdeploy";
if (options.configuration.userAgentApp) {
userAgent = `${userAgent} ${options.configuration.userAgentApp}`;
}
config.headers["User-Agent"] = userAgent;
config.headers["User-Agent"] = createUserAgent(options.configuration);
}
}
const response = await axios.request<TResource>(config);
Expand Down
30 changes: 30 additions & 0 deletions src/adapters/createUserAgent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ClientConfiguration } from "../clientConfiguration";
import { createUserAgent } from "./createUserAgent";

describe("createUserAgent", () => {
const configuration: ClientConfiguration = {
instanceURL: "https://my.octopus.app",
userAgentApp: "octopus-mcp-server/1.2.3 (claude-code/2.1.42)",
};

test("is unchanged when no agent is detected", () => {
expect(createUserAgent(configuration, {})).toBe("ts-octopusdeploy octopus-mcp-server/1.2.3 (claude-code/2.1.42)");
});

test("keeps the existing header and appends the agent", () => {
const withoutAgent = createUserAgent(configuration, {});
expect(createUserAgent(configuration, { CLAUDECODE: "1" })).toBe(`${withoutAgent} (ai-agent=ClaudeCode)`);
});

test("uses the caller-supplied agent", () => {
expect(createUserAgent({ ...configuration, aiAgent: "claude-code" }, {})).toBe(
"ts-octopusdeploy octopus-mcp-server/1.2.3 (claude-code/2.1.42) (ai-agent=ClaudeCode)"
);
});

test("ignores a caller-supplied agent that isn't a string", () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const aiAgent = 42 as unknown as string;
expect(createUserAgent({ ...configuration, aiAgent }, {})).toBe("ts-octopusdeploy octopus-mcp-server/1.2.3 (claude-code/2.1.42)");
});
});
8 changes: 8 additions & 0 deletions src/adapters/createUserAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { getAiAgentUserAgentToken } from "../aiAgent";
import type { ClientConfiguration } from "../clientConfiguration";

export function createUserAgent(configuration: ClientConfiguration, env?: Record<string, string | undefined>): string {
// The agent is appended last so everything before it is unchanged: Octopus Server matches on the start of this header,
// e.g. "ts-octopusdeploy octopus-mcp-server" for the local MCP server.
return ["ts-octopusdeploy", configuration.userAgentApp, getAiAgentUserAgentToken(configuration.aiAgent, env)].filter((part) => !!part).join(" ");
}
65 changes: 65 additions & 0 deletions src/aiAgent.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { getAiAgentUserAgentToken } from "./aiAgent";

describe("getAiAgentUserAgentToken", () => {
test("returns undefined when no agent is detected", () => {
expect(getAiAgentUserAgentToken(undefined, {})).toBeUndefined();
});

test("detects an agent from a vendor variable", () => {
expect(getAiAgentUserAgentToken(undefined, { CLAUDECODE: "1" })).toBe("(ai-agent=ClaudeCode)");
});

test.each([
["CURSOR_EXTENSION_HOST_ROLE", "agent-exec", "(ai-agent=Cursor)"],
["CURSOR_EXTENSION_HOST_ROLE", "user", undefined],
["AGENT", "amp", "(ai-agent=Amp)"],
["AGENT", "teamcity-agent-01", undefined],
])("requires a matching value for %s=%s", (variable, value, expected) => {
expect(getAiAgentUserAgentToken(undefined, { [variable]: value })).toBe(expected);
});

test.each(["CURSOR_TRACE_ID", "COPILOT_GITHUB_TOKEN"])("ignores %s, which is set without an agent", (variable) => {
expect(getAiAgentUserAgentToken(undefined, { [variable]: "1" })).toBeUndefined();
});

test("the first known agent wins when agents are nested", () => {
expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", CLAUDECODE: "1" })).toBe("(ai-agent=ClaudeCode)");
});

test.each([
["claude-code_2-1-322_agent", "(ai-agent=ClaudeCode)"],
["Claude Code", "(ai-agent=ClaudeCode)"],
["github_copilot_vscode_agent", "(ai-agent=GitHubCopilot)"],
["devin@1", "(ai-agent=Devin)"],
["custom-agent@2.0", "(ai-agent=Other)"],
["amplitude-mcp", "(ai-agent=Other)"],
])("maps AI_AGENT=%s to %s", (value, expected) => {
expect(getAiAgentUserAgentToken(undefined, { AI_AGENT: value })).toBe(expected);
});

test("AI_AGENT takes precedence over vendor variables", () => {
expect(getAiAgentUserAgentToken(undefined, { CURSOR_AGENT: "1", AI_AGENT: "claude-code_2-1-322_agent" })).toBe("(ai-agent=ClaudeCode)");
});

test("an unrecognised AI_AGENT falls back to the vendor name", () => {
expect(getAiAgentUserAgentToken(undefined, { GEMINI_CLI: "1", AI_AGENT: "gcli" })).toBe("(ai-agent=GeminiCLI)");
});

test.each([
[" evil) agent\r\nX-Injected: 1 ", "(ai-agent=Other)"],
[" \t ", undefined],
])("never includes the raw AI_AGENT value (%j)", (value, expected) => {
expect(getAiAgentUserAgentToken(undefined, { AI_AGENT: value })).toBe(expected);
});

describe("caller-supplied agent", () => {
test("takes precedence over AI_AGENT and vendor variables", () => {
expect(getAiAgentUserAgentToken("cursor-vscode", { AI_AGENT: "claude-code", CLAUDECODE: "1" })).toBe("(ai-agent=Cursor)");
});

test("falls back to AI_AGENT when not recognised, and reports as Other when nothing is", () => {
expect(getAiAgentUserAgentToken("some-mcp-client", { AI_AGENT: "claude-code" })).toBe("(ai-agent=ClaudeCode)");
expect(getAiAgentUserAgentToken("some-mcp-client", {})).toBe("(ai-agent=Other)");
});
});
});
138 changes: 138 additions & 0 deletions src/aiAgent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// The agent list is maintained in go-octopusdeploy and ported from there; keep in sync.
// https://github.com/OctopusDeploy/go-octopusdeploy/blob/main/pkg/services/api/ai_agent_provider.go
//
// Detection relies on self-reported values, so it is suitable for analytics but must not be relied on for
// security decisions.

type EnvironmentVariables = Record<string, string | undefined>;

interface AgentRule {
variable: string;
// When set, the variable's value must match (case-insensitive). Otherwise any non-empty value matches.
value?: string;
}

// The emerging cross-vendor convention for an agent to identify itself.
// https://github.com/vercel/vercel/tree/main/packages/detect-agent
const aiAgentVariable = "AI_AGENT";

const otherAgentName = "Other";

interface KnownAgent {
name: string;
// When set, matches the start of a normalised self-reported identifier. Vendors don't agree on a format
// (e.g. "claude-code_2-1-322_agent", "github_copilot_vscode_agent", "devin@1"), so identifiers are lowercased
// and runs of underscores and whitespace replaced with a single hyphen before matching.
aiAgentPrefix?: string;
// Vendor-specific environment variables that identify the agent.
variables?: AgentRule[];
}

// Each agent is listed once, and can be recognised from a self-reported identifier (by prefix), from its vendor
// variables, or both. Self-reported identifiers are checked against the whole list before any vendor variables, so a
// self-reported identity wins (e.g. Claude Code running inside Cursor). Within each lookup the first match wins, so
// the result is deterministic when several agents' variables are present.
//
// Variables that are commonly present without an agent driving the process are deliberately excluded:
// CURSOR_TRACE_ID (any Cursor terminal), COPILOT_GITHUB_TOKEN and GOOSE_PROVIDER (user configuration),
// REPL_ID (any Replit workspace) and ZED_TERM (any Zed terminal).
const knownAgents: ReadonlyArray<KnownAgent> = [
{ name: "ClaudeCode", aiAgentPrefix: "claude-code", variables: [{ variable: "CLAUDECODE" }, { variable: "CLAUDE_CODE_ENTRYPOINT" }] },
{ name: "Cursor", aiAgentPrefix: "cursor", variables: [{ variable: "CURSOR_AGENT" }, { variable: "CURSOR_EXTENSION_HOST_ROLE", value: "agent-exec" }] },
{ name: "Codex", aiAgentPrefix: "codex", variables: [{ variable: "CODEX_SANDBOX" }, { variable: "CODEX_THREAD_ID" }, { variable: "CODEX_CI" }] },
{ name: "GeminiCLI", aiAgentPrefix: "gemini", variables: [{ variable: "GEMINI_CLI" }] },
{
name: "GitHubCopilot",
aiAgentPrefix: "github-copilot",
variables: [{ variable: "COPILOT_CLI" }, { variable: "COPILOT_AGENT" }, { variable: "GITHUB_COPILOT_CLI_MODE" }],
},
{
name: "OpenCode",
aiAgentPrefix: "opencode",
variables: [{ variable: "OPENCODE", value: "1" }, { variable: "OPENCODE_CLIENT" }, { variable: "OPENCODE_AI" }],
},
{ name: "Antigravity", aiAgentPrefix: "antigravity", variables: [{ variable: "ANTIGRAVITY_AGENT" }] },
{ name: "Goose", aiAgentPrefix: "goose", variables: [{ variable: "GOOSE_TERMINAL" }, { variable: "AGENT", value: "goose" }] },
{ name: "Amp", aiAgentPrefix: "amp", variables: [{ variable: "AGENT", value: "amp" }] },
{ name: "Cline", aiAgentPrefix: "cline", variables: [{ variable: "CLINE_ACTIVE" }, { variable: "CLINE_TASK_ID" }] },
{ name: "RooCode", variables: [{ variable: "ROO_CODE_TASK_ID" }] },
{ name: "Augment", aiAgentPrefix: "augment", variables: [{ variable: "AUGMENT_AGENT" }] },
{ name: "QwenCode", variables: [{ variable: "QWEN_CODE" }] },
{ name: "FactoryDroid", variables: [{ variable: "DROID_CLI" }] },
{ name: "KimiCLI", variables: [{ variable: "KIMI_CLI" }] },
{ name: "Trae", variables: [{ variable: "TRAE_AI_SHELL_ID" }] },
{ name: "Aider", variables: [{ variable: "OR_APP_NAME", value: "Aider" }] },
{ name: "OpenHands", variables: [{ variable: "OR_APP_NAME", value: "OpenHands" }] },
{ name: "Devin", aiAgentPrefix: "devin" },
{ name: "Replit", aiAgentPrefix: "replit" },
{ name: "V0", aiAgentPrefix: "v0" },
];

/**
* Returns a User-Agent comment naming the AI agent driving this client (e.g. "(ai-agent=ClaudeCode)"), or undefined
* when none is detected.
*
* Self-reported identifiers are checked first, in order: an identifier supplied by the caller (for example an MCP
* server passing the connected client's `clientInfo.name`), then the `AI_AGENT` environment variable. If neither is
* recognised, vendor-specific environment variables are checked. An identifier that is present but not recognised
* reports as "(ai-agent=Other)". Only the normalised name is reported: raw identifiers are free-form, so they are used
* for matching and never included in the output.
*/
export function getAiAgentUserAgentToken(callerSuppliedAgent?: string, env?: EnvironmentVariables): string | undefined {
try {
const variables = env ?? readProcessEnvironment();
const aiAgentNameFromEnvVar = variables[aiAgentVariable];
const selfReported = [callerSuppliedAgent, aiAgentNameFromEnvVar]
.map((value) => (typeof value === "string" ? value.trim() : undefined))
.filter((value): value is string => !!value);

// Vendor variables also cover an agent that self-reports in a format that isn't recognised.
const agent = selfReported.map(findAgentByPrefix).find((a): a is KnownAgent => a !== undefined) ?? findAgentByVariables(variables);
if (agent) {
return aiAgentComment(agent.name);
}

return selfReported.length > 0 ? aiAgentComment(otherAgentName) : undefined;
} catch {
// Detection is best-effort and must never fail a request, e.g. where reading the environment isn't permitted.
return undefined;
}
}

// Formats the agent as an RFC 9110 comment, so it describes the request rather than claiming to be a product in the
// User-Agent.
function aiAgentComment(name: string): string {
return `(ai-agent=${name})`;
}

function findAgentByPrefix(identifier: string): KnownAgent | undefined {
const normalised = identifier.toLowerCase().replace(/[_\s]+/g, "-");
return knownAgents.find((agent) => agent.aiAgentPrefix !== undefined && matchesPrefix(normalised, agent.aiAgentPrefix));
}

// Whether the identifier starts with the prefix followed by the end of the identifier, or by a separator ("-", "@", ".")
// or digit, so a short prefix such as "amp" doesn't match an unrelated identifier such as "amplitude-mcp".
function matchesPrefix(identifier: string, prefix: string): boolean {
if (!identifier.startsWith(prefix)) {
return false;
}
const next = identifier.charAt(prefix.length);
return next === "" || /^[-@.0-9]$/.test(next);
}
Comment thread
zentron marked this conversation as resolved.
Resolved

function findAgentByVariables(env: EnvironmentVariables): KnownAgent | undefined {
return knownAgents.find((agent) =>
(agent.variables ?? []).some((rule) => {
const value = env[rule.variable];
if (!value) {
return false;
}
return rule.value === undefined || value.toLowerCase() === rule.value.toLowerCase();
})
);
}

function readProcessEnvironment(): EnvironmentVariables {
// The client also runs in browsers, where there is no process environment to read.
return typeof process !== "undefined" && process.env ? process.env : {};
}
1 change: 1 addition & 0 deletions src/clientConfiguration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Logger } from "./logger";

export interface ClientConfiguration {
userAgentApp: string;
aiAgent?: string;
httpsAgent?: Agent;
apiKey?: string;
accessToken?: string;
Expand Down
Loading