From 946e4dd0530cbda6a1c6cb361e0880c9a83b6f3a Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Fri, 11 Sep 2026 15:26:44 -0400 Subject: [PATCH 01/45] feat: add support for agents metadata env vars --- src/cmap/handshake/client_metadata.ts | 79 ++++++++++++++--- .../mongodb-handshake.prose.test.ts | 87 +++++++++++++++++++ 2 files changed, 155 insertions(+), 11 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 587d3420b9..717d80dbfc 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -44,16 +44,17 @@ export interface ClientMetadata { application?: { name: string; }; - /** FaaS environment information */ env?: { - name?: 'aws.lambda' | 'gcp.func' | 'azure.func' | 'vercel'; - timeout_sec?: Int32; - memory_mb?: Int32; - region?: string; + agent?: string; container?: { runtime?: string; orchestrator?: string; }; + /** FaaS environment information */ + name?: 'aws.lambda' | 'gcp.func' | 'azure.func' | 'vercel'; + timeout_sec?: Int32; + memory_mb?: Int32; + region?: string; }; } @@ -100,7 +101,7 @@ type MakeClientMetadataOptions = Pick; /** * From the specs: * Implementors SHOULD cumulatively update fields in the following order until the document is under the size limit: - * 1. Omit fields from `env` except `env.name`. + * 1. Omit fields from `env` except `env.name` & `env.agent`. * 2. Omit fields from `os` except `os.type`. * 3. Omit the `env` document entirely. * 4. Truncate `platform`. -- special we do not truncate this field @@ -181,7 +182,9 @@ export async function makeClientMetadata( } } } - return await addContainerMetadata(metadataDocument.toObject() as ClientMetadata); + + const metadata = await addContainerMetadata(metadataDocument.toObject() as ClientMetadata); + return addAgentMetadata(metadata); } let dockerPromise: Promise; @@ -204,18 +207,33 @@ async function getContainerMetadata(): Promise { /** * @internal - * Re-add each metadata value. * Attempt to add new env container metadata, but keep old data if it does not fit. */ async function addContainerMetadata(originalMetadata: ClientMetadata): Promise { - const containerMetadata = await getContainerMetadata(); - if (Object.keys(containerMetadata).length === 0) return originalMetadata; + return extendEnvMetadata(originalMetadata, 'container', await getContainerMetadata()); +} + +/** + * @internal + * Re-add each metadata value. + * Attempt to add `env[metadataKey]`, but keep old data if it does not fit. + */ +function extendEnvMetadata( + originalMetadata: ClientMetadata, + metadataKey: 'container' | 'agent', + metadataValue: ContainerMetadata | string +): ClientMetadata { + const isEmpty = + typeof metadataValue === 'string' + ? metadataValue.length === 0 + : Object.keys(metadataValue).length === 0; + if (isEmpty) return originalMetadata; const extendedMetadata = new LimitedSizeDocument(512); const extendedEnvMetadata: NonNullable = { ...originalMetadata?.env, - container: containerMetadata + [metadataKey]: metadataValue }; for (const [key, val] of Object.entries(originalMetadata)) { @@ -236,6 +254,45 @@ async function addContainerMetadata(originalMetadata: ClientMetadata): Promise = [ + ['AI_AGENT', null], + ['AGENT', null], + ['CLAUDECODE', 'claude-code'], + ['CURSOR_AGENT', 'cursor'], + ['GEMINI_CLI', 'gemini-cli'], + ['CODEX_SANDBOX', 'codex'], + ['AUGMENT_AGENT', 'augment'], + ['OPENCODE_CLIENT', 'opencode'] +]; + +/** + * @internal + * Attempt to add new env agent metadata, but keep old data if it does not fit. + * + * From the spec: + * client.env.agent is a single string. Its value is determined by the environment variables below. + * Drivers MUST evaluate the list in order. The first populated variable determines the value, and + * subsequent entries MUST NOT be considered. + */ +function addAgentMetadata(originalMetadata: ClientMetadata): ClientMetadata { + let agent = ''; + + for (const [key, value] of AGENT_ENV_VARIABLES) { + const envValue = process.env[key] ?? ''; + if (envValue.length > 0) { + agent = value ?? envValue; + break; + } + } + + return extendEnvMetadata(originalMetadata, 'agent', agent); +} + /** * Collects FaaS metadata. * - `name` MUST be the last key in the Map returned. diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 7ee7a361ed..2b44af8724 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -202,6 +202,93 @@ describe('Handshake Prose Tests', function () { await client.close(); }); }); + + context(`Test 3: Test that agent metadata is properly captured`, function () { + const agentEnvs: Array<{ + expectEnv: Object; + env?: EnvironmentVariables; + }> = [ + { + env: [ + ['AI_AGENT', 'custom-agent'], + ], + expectEnv: { + agent: 'custom-agent' + } + }, + { + env: [['AGENT', 'custom-agent']], + expectEnv: { + agent: 'custom-agent' + } + }, + { + env: [ + ['CLAUDE_CODE', '1'], + ], + expectEnv: { + agent: 'claude-code' + } + }, + { + env: [ + ['AI_AGENT', 'custom-agent'], + ['CLAUDECODE', '1'] + ], + expectEnv: { + agent: 'custom-agent' + } + }, + { + env: [ + ['CURSOR_AGENT', '1'], + ['GEMINI_CLI', '1'] + ], + expectEnv: { + agent: 'cursor' + } + }, + { + env: [ + ['AI_AGENT', ''], + ], + expectEnv: null + }, + { + env: [ + ['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'], + ['AWS_REGION', 'us-east-2'], + ['CLAUDECODE', '1'] + ], + expectEnv: { + agent: 'claude-code', + region: 'us-east-2', + name: 'aws.lambda', + } + } + ]; + + for (const [i, { env, expectEnv }] of agentEnvs.entries()) { + context(`Test 3: Test that agent metadata is properly captured #${i}`, function () { + stubEnv(env); + + it('runs a hello successfully', async function () { + client = this.configuration.newClient({ + serverSelectionTimeoutMS: 3000 + }); + // Facilitates hello via connect() + await client.connect(); + + expect(client.topology?.s.options.metadata).to.exist; + const { env } = await client.topology.s.options.metadata; + + expect(env).to.deep.equal(expectEnv); + + }); + }); + } + }); + }); describe('Client Metadata Update Prose Tests', function () { From 0bc4c2d73c8ed630dd5edd56a60a18b0b3f354fd Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Fri, 11 Sep 2026 15:45:38 -0400 Subject: [PATCH 02/45] test: add & fix prose tests --- .../mongodb-handshake.prose.test.ts | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 2b44af8724..692662abeb 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -203,11 +203,14 @@ describe('Handshake Prose Tests', function () { }); }); + // Ref: https://github.com/aclark4life/specifications/blob/feaec8d0ca332a80f457f75c6ef1600267e61d64/source/mongodb-handshake/tests/README.md#test-3-test-that-agent-metadata-is-properly-captured + // TODO: Update link when fixed to main branch context(`Test 3: Test that agent metadata is properly captured`, function () { const agentEnvs: Array<{ expectEnv: Object; env?: EnvironmentVariables; }> = [ + // 1. Generic agent via AI_AGENT. client.env.agent MUST equal custom-agent. { env: [ ['AI_AGENT', 'custom-agent'], @@ -216,20 +219,23 @@ describe('Handshake Prose Tests', function () { agent: 'custom-agent' } }, + // 2. Generic agent via AGENT. client.env.agent MUST equal custom-agent. { env: [['AGENT', 'custom-agent']], expectEnv: { agent: 'custom-agent' } }, + // 3. Known agent. client.env.agent MUST equal claude-code. { env: [ - ['CLAUDE_CODE', '1'], + ['CLAUDECODE', '1'], ], expectEnv: { agent: 'claude-code' } }, + // 4. Precedence - generic wins over known. client.env.agent MUST equal custom-agent (the value of AI_AGENT), not claude-code. { env: [ ['AI_AGENT', 'custom-agent'], @@ -239,6 +245,7 @@ describe('Handshake Prose Tests', function () { agent: 'custom-agent' } }, + // 5. Precedence - first known wins. client.env.agent MUST equal cursor. { env: [ ['CURSOR_AGENT', '1'], @@ -248,12 +255,19 @@ describe('Handshake Prose Tests', function () { agent: 'cursor' } }, + // 6. Empty value is treated as unset. client.env.agent MUST be omitted. If no other client.env fields are populated, client.env MUST be entirely omitted. { env: [ ['AI_AGENT', ''], ], - expectEnv: null + expectEnv: undefined, }, + // 7. No agent variables. None of the environment variables in the client.env.agent table are set. client.env.agent MUST be omitted. + { + env: [], + expectEnv: undefined, + }, + // 8. Agent alongside FaaS. This test MUST verify that both the AWS Lambda metadata and client.env.agent (equal to claude-code) are present in client.env. { env: [ ['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'], @@ -269,7 +283,7 @@ describe('Handshake Prose Tests', function () { ]; for (const [i, { env, expectEnv }] of agentEnvs.entries()) { - context(`Test 3: Test that agent metadata is properly captured #${i}`, function () { + context(`Test 3: Test that agent metadata is properly captured #${i+1}`, function () { stubEnv(env); it('runs a hello successfully', async function () { From e1215c14bb025d3d7a6c3c6f966c759ee91fb379 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 14 Sep 2026 12:37:35 -0400 Subject: [PATCH 03/45] chore: lint --- src/cmap/handshake/client_metadata.ts | 14 +++++++---- .../mongodb-handshake.prose.test.ts | 24 +++++++------------ 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 717d80dbfc..fa7887556c 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -213,6 +213,12 @@ async function addContainerMetadata(originalMetadata: ClientMetadata): Promise = [ ['AI_AGENT', null], diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 692662abeb..97c2f401ec 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -207,14 +207,12 @@ describe('Handshake Prose Tests', function () { // TODO: Update link when fixed to main branch context(`Test 3: Test that agent metadata is properly captured`, function () { const agentEnvs: Array<{ - expectEnv: Object; + expectEnv: object; env?: EnvironmentVariables; }> = [ // 1. Generic agent via AI_AGENT. client.env.agent MUST equal custom-agent. { - env: [ - ['AI_AGENT', 'custom-agent'], - ], + env: [['AI_AGENT', 'custom-agent']], expectEnv: { agent: 'custom-agent' } @@ -228,9 +226,7 @@ describe('Handshake Prose Tests', function () { }, // 3. Known agent. client.env.agent MUST equal claude-code. { - env: [ - ['CLAUDECODE', '1'], - ], + env: [['CLAUDECODE', '1']], expectEnv: { agent: 'claude-code' } @@ -257,15 +253,13 @@ describe('Handshake Prose Tests', function () { }, // 6. Empty value is treated as unset. client.env.agent MUST be omitted. If no other client.env fields are populated, client.env MUST be entirely omitted. { - env: [ - ['AI_AGENT', ''], - ], - expectEnv: undefined, + env: [['AI_AGENT', '']], + expectEnv: undefined }, // 7. No agent variables. None of the environment variables in the client.env.agent table are set. client.env.agent MUST be omitted. { env: [], - expectEnv: undefined, + expectEnv: undefined }, // 8. Agent alongside FaaS. This test MUST verify that both the AWS Lambda metadata and client.env.agent (equal to claude-code) are present in client.env. { @@ -277,13 +271,13 @@ describe('Handshake Prose Tests', function () { expectEnv: { agent: 'claude-code', region: 'us-east-2', - name: 'aws.lambda', + name: 'aws.lambda' } } ]; for (const [i, { env, expectEnv }] of agentEnvs.entries()) { - context(`Test 3: Test that agent metadata is properly captured #${i+1}`, function () { + context(`Test 3: Test that agent metadata is properly captured #${i + 1}`, function () { stubEnv(env); it('runs a hello successfully', async function () { @@ -297,12 +291,10 @@ describe('Handshake Prose Tests', function () { const { env } = await client.topology.s.options.metadata; expect(env).to.deep.equal(expectEnv); - }); }); } }); - }); describe('Client Metadata Update Prose Tests', function () { From 5e33f771834b5b8e875a87dc47b9f5bcbaedbf5b Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 14 Sep 2026 13:02:05 -0400 Subject: [PATCH 04/45] fix: trim() incoming agent values --- src/cmap/handshake/client_metadata.ts | 2 +- .../cmap/handshake/client_metadata.test.ts | 79 +++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index fa7887556c..1f6fde10b8 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -290,7 +290,7 @@ function addAgentMetadata(originalMetadata: ClientMetadata): ClientMetadata { for (const [key, value] of AGENT_ENV_VARIABLES) { const envValue = process.env[key] ?? ''; - if (envValue.length > 0) { + if (envValue.trim().length > 0) { agent = value ?? envValue; break; } diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index be8e2c2ca2..bb0df6114c 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -623,4 +623,83 @@ describe('client metadata module', () => { }); }); }); + + describe('agent metadata', function () { + context('when a known agent variable is set to an arbitrary value', function () { + beforeEach(function () { + sinon.stub(process, 'env').get(() => ({ GEMINI_CLI: 'some-other-value' })); + }); + + it('ignores the value and uses the value from the agent table', async function () { + const metadata = await makeClientMetadata([], { runtime }); + expect(metadata).to.have.nested.property('env.agent', 'gemini-cli'); + }); + }); + + context('when AI_AGENT is set to a whitespace-only string', function () { + beforeEach(function () { + sinon.stub(process, 'env').get(() => ({ AI_AGENT: ' ' })); + }); + + it('treats the variable as unpopulated', async function () { + const metadata = await makeClientMetadata([], { runtime }); + expect(metadata).to.not.have.property('env'); + }); + }); + }); + + describe('env metadata extension', function () { + context('when the agent is added to metadata without an env document', function () { + beforeEach(function () { + sinon.stub(process, 'env').get(() => ({ AI_AGENT: 'custom-agent' })); + }); + + it('leaves the non-env metadata fields untouched', async function () { + const metadata = await makeClientMetadata([], { runtime }); + expect(metadata).to.deep.equal({ + driver: { + name: 'nodejs', + version: NODE_DRIVER_VERSION + }, + os: { + type: os.type(), + name: os.platform(), + architecture: os.arch(), + version: os.release() + }, + platform: `Node.js ${process.version}, ${os.endianness()}`, + env: { agent: 'custom-agent' } + }); + }); + }); + + context('when the agent does not fit and there is an existing env document', function () { + beforeEach(function () { + sinon.stub(process, 'env').get(() => ({ + AWS_EXECUTION_ENV: 'AWS_Lambda_java8', + AWS_REGION: 'us-east-2', + AI_AGENT: 'a'.repeat(512) + })); + }); + + it('keeps the original env document', async function () { + const metadata = await makeClientMetadata([], { runtime }); + expect(metadata.env).to.deep.equal({ + name: 'aws.lambda', + region: 'us-east-2' + }); + }); + }); + + context('when the agent does not fit and there is no existing env document', function () { + beforeEach(function () { + sinon.stub(process, 'env').get(() => ({ AI_AGENT: 'a'.repeat(512) })); + }); + + it('omits the env document entirely', async function () { + const metadata = await makeClientMetadata([], { runtime }); + expect(metadata).to.not.have.property('env'); + }); + }); + }); }); From ba77233f47843e499d309f18beb191f730f936b5 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 14 Sep 2026 14:44:49 -0400 Subject: [PATCH 05/45] chore: fix val interpretation --- src/cmap/handshake/client_metadata.ts | 33 +++-- .../cmap/handshake/client_metadata.test.ts | 128 +++++++++++------- 2 files changed, 100 insertions(+), 61 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 1f6fde10b8..f689d8c142 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -224,7 +224,7 @@ type EnvMetadataEntry = ['container', ContainerMetadata] | ['agent', string]; * Re-add each metadata value. * Attempt to add `env[metadataKey]`, but keep old data if it does not fit. */ -function extendEnvMetadata( +export function extendEnvMetadata( originalMetadata: ClientMetadata, ...[metadataKey, metadataValue]: EnvMetadataEntry ): ClientMetadata { @@ -263,7 +263,12 @@ function extendEnvMetadata( * @internal * Environment variables that indicate the driver is being used by an AI agent, in the order the * spec requires them to be evaluated. [0] is the environment variable, [1] is the value to set - * when that environment variable is encountered. If [1] is null, use the environment variable value. + * when that environment variable is encountered. If [1] is null, use the (trimmed) environment variable value. + * + * From the spec: + * client.env.agent is a single string. Its value is determined by the environment variables below. + * Drivers MUST evaluate the list in order. The first populated variable determines the value, and + * subsequent entries MUST NOT be considered. */ const AGENT_ENV_VARIABLES: ReadonlyArray = [ ['AI_AGENT', null], @@ -279,24 +284,28 @@ const AGENT_ENV_VARIABLES: ReadonlyArray = [ /** * @internal * Attempt to add new env agent metadata, but keep old data if it does not fit. - * - * From the spec: - * client.env.agent is a single string. Its value is determined by the environment variables below. - * Drivers MUST evaluate the list in order. The first populated variable determines the value, and - * subsequent entries MUST NOT be considered. */ function addAgentMetadata(originalMetadata: ClientMetadata): ClientMetadata { - let agent = ''; + return extendEnvMetadata(originalMetadata, 'agent', getAgentEnv()); +} - for (const [key, value] of AGENT_ENV_VARIABLES) { +/** + * @internal + * Resolves `env.agent` from the environment, or an empty string when no agent variable is + * populated. Returns the value of the first populated variable in `AGENT_ENV_VARIABLES`. + */ +export function getAgentEnv(): string { + for (const [key, literal] of AGENT_ENV_VARIABLES) { + // A variable is only populated if it is present with a non-empty value, so an empty or + // whitespace-only value never selects an entry, even one with a fixed table value. + // A populated value is reported verbatim; only the populated check ignores whitespace. const envValue = process.env[key] ?? ''; if (envValue.trim().length > 0) { - agent = value ?? envValue; - break; + return literal ?? envValue; } } - return extendEnvMetadata(originalMetadata, 'agent', agent); + return ''; } /** diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index bb0df6114c..96fcfc74d4 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -7,6 +7,9 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { + type ClientMetadata, + extendEnvMetadata, + getAgentEnv, getFAASEnv, LimitedSizeDocument, makeClientMetadata, @@ -624,81 +627,108 @@ describe('client metadata module', () => { }); }); - describe('agent metadata', function () { - context('when a known agent variable is set to an arbitrary value', function () { + describe('getAgentEnv()', function () { + const stubEnv = (env: NodeJS.ProcessEnv) => { beforeEach(function () { - sinon.stub(process, 'env').get(() => ({ GEMINI_CLI: 'some-other-value' })); + sinon.stub(process, 'env').get(() => env); }); + }; - it('ignores the value and uses the value from the agent table', async function () { - const metadata = await makeClientMetadata([], { runtime }); - expect(metadata).to.have.nested.property('env.agent', 'gemini-cli'); + context('when a fixed-value agent variable is set to an arbitrary value', function () { + stubEnv({ GEMINI_CLI: 'some-other-value' }); + + it('returns the value from the agent table, not the environment', function () { + expect(getAgentEnv()).to.equal('gemini-cli'); }); }); - context('when AI_AGENT is set to a whitespace-only string', function () { - beforeEach(function () { - sinon.stub(process, 'env').get(() => ({ AI_AGENT: ' ' })); - }); + context('when a generic agent variable is padded with whitespace', function () { + stubEnv({ AI_AGENT: ' custom-agent ' }); - it('treats the variable as unpopulated', async function () { - const metadata = await makeClientMetadata([], { runtime }); - expect(metadata).to.not.have.property('env'); + it('returns the value verbatim', function () { + expect(getAgentEnv()).to.equal(' custom-agent '); }); }); + + // 'A variable is considered populated if it is present in the environment with a non-empty + // value.' & 'The first populated variable determines the value, and subsequent entries MUST NOT be considered.' + const unpopulated: Array = ['', ' ', undefined]; + + for (const value of unpopulated) { + // A generic and a literal + for (const key of ['AI_AGENT', 'CLAUDECODE']) { + context(`when ${key} is set to "${value}"`, function () { + stubEnv({ [key]: value }); + + it('treats the variable as unpopulated', function () { + expect(getAgentEnv()).to.equal(''); + }); + }); + } + + context(`when an earlier variable is set to "${value}"`, function () { + stubEnv({ AI_AGENT: value, CLAUDECODE: '1' }); + + it('skips it and considers the next variable', function () { + expect(getAgentEnv()).to.equal('claude-code'); + }); + }); + } }); - describe('env metadata extension', function () { - context('when the agent is added to metadata without an env document', function () { - beforeEach(function () { - sinon.stub(process, 'env').get(() => ({ AI_AGENT: 'custom-agent' })); + describe('extendEnvMetadata()', function () { + const metadata: ClientMetadata = { + driver: { name: 'nodejs', version: NODE_DRIVER_VERSION }, + os: { type: 'Linux' }, + platform: 'Node.js v20.0.0, LE' + }; + + // 'If none of the variables above are populated, client.env.agent MUST be entirely omitted.' + context('when the value is empty', function () { + it('returns the metadata unchanged for a string value', function () { + expect(extendEnvMetadata(metadata, 'agent', '')).to.deep.equal(metadata); }); - it('leaves the non-env metadata fields untouched', async function () { - const metadata = await makeClientMetadata([], { runtime }); - expect(metadata).to.deep.equal({ - driver: { - name: 'nodejs', - version: NODE_DRIVER_VERSION - }, - os: { - type: os.type(), - name: os.platform(), - architecture: os.arch(), - version: os.release() - }, - platform: `Node.js ${process.version}, ${os.endianness()}`, + it('returns the metadata unchanged for a document value', function () { + expect(extendEnvMetadata(metadata, 'container', {})).to.deep.equal(metadata); + }); + }); + + context('when the metadata has no env document', function () { + it('adds the env document and leaves the other fields untouched', function () { + expect(extendEnvMetadata(metadata, 'agent', 'custom-agent')).to.deep.equal({ + ...metadata, env: { agent: 'custom-agent' } }); }); }); - context('when the agent does not fit and there is an existing env document', function () { - beforeEach(function () { - sinon.stub(process, 'env').get(() => ({ - AWS_EXECUTION_ENV: 'AWS_Lambda_java8', - AWS_REGION: 'us-east-2', - AI_AGENT: 'a'.repeat(512) - })); + context('when the metadata has an existing env document', function () { + it('merges the new key into the existing env document', function () { + const withAgent: ClientMetadata = { ...metadata, env: { agent: 'custom-agent' } }; + expect(extendEnvMetadata(withAgent, 'container', { runtime: 'docker' })).to.deep.equal({ + ...metadata, + env: { agent: 'custom-agent', container: { runtime: 'docker' } } + }); }); + }); - it('keeps the original env document', async function () { - const metadata = await makeClientMetadata([], { runtime }); - expect(metadata.env).to.deep.equal({ + context('when the new value does not fit and there is an existing env document', function () { + it('keeps the original env document', function () { + const withEnv: ClientMetadata = { + ...metadata, + env: { name: 'aws.lambda', region: 'us-east-2' } + }; + expect(extendEnvMetadata(withEnv, 'agent', 'a'.repeat(512)).env).to.deep.equal({ name: 'aws.lambda', region: 'us-east-2' }); }); }); - context('when the agent does not fit and there is no existing env document', function () { - beforeEach(function () { - sinon.stub(process, 'env').get(() => ({ AI_AGENT: 'a'.repeat(512) })); - }); - - it('omits the env document entirely', async function () { - const metadata = await makeClientMetadata([], { runtime }); - expect(metadata).to.not.have.property('env'); + context('when the new value does not fit and there is no existing env document', function () { + it('omits the env document entirely', function () { + expect(extendEnvMetadata(metadata, 'agent', 'a'.repeat(512))).to.not.have.property('env'); }); }); }); From e3be6c4c47ba8fe16369ab5df6dadc20c2253c7a Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 14 Sep 2026 15:44:40 -0400 Subject: [PATCH 06/45] fix: preserve key deletion order and matchp ref of agent & name --- src/cmap/handshake/client_metadata.ts | 105 +++++------------- .../cmap/handshake/client_metadata.test.ts | 90 ++++----------- 2 files changed, 49 insertions(+), 146 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index f689d8c142..1dcd35f757 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -172,98 +172,53 @@ export async function makeClientMetadata( } } + // Env has an order of precedence for data truncation, and order matters. + // We append in the order of delete preference. 'name' is appended at the end of + // faasEnv, and is preference-agnostic with 'agent'. So we'll prefer keeping + // 'agent' over 'name', and 'name' over all FAAS props, and all FAAS props + // over 'container' (since FAAS props and 'container' are preference-agnostic as well) + const containerMetadata = await getContainerMetadata(); const faasEnv = getFAASEnv(); - if (faasEnv != null) { - if (!metadataDocument.ifItFitsItSits('env', faasEnv)) { - for (const key of faasEnv.keys()) { - faasEnv.delete(key); - if (faasEnv.size === 0) break; - if (metadataDocument.ifItFitsItSits('env', faasEnv)) break; - } + const agentEnv = getAgentEnv(); + + const fullEnv = new Map(); + if (containerMetadata.size > 0) fullEnv.set('container', containerMetadata); + for (const [k, v] of faasEnv) fullEnv.set(k, v); + if (agentEnv.length > 0) fullEnv.set('agent', agentEnv); + + if (fullEnv.size > 0 && !metadataDocument.ifItFitsItSits('env', fullEnv)) { + for (const key of fullEnv.keys()) { + fullEnv.delete(key); + if (fullEnv.size === 0) break; + if (metadataDocument.ifItFitsItSits('env', fullEnv)) break; } } - const metadata = await addContainerMetadata(metadataDocument.toObject() as ClientMetadata); - return addAgentMetadata(metadata); + return metadataDocument.toObject() as ClientMetadata; } let dockerPromise: Promise; -type ContainerMetadata = NonNullable['container']>; /** @internal */ -async function getContainerMetadata(): Promise { +async function getContainerMetadata(): Promise> { dockerPromise ??= fileIsAccessible('/.dockerenv'); const isDocker = await dockerPromise; const { KUBERNETES_SERVICE_HOST = '' } = process.env; const isKubernetes = KUBERNETES_SERVICE_HOST.length > 0 ? true : false; - const containerMetadata: ContainerMetadata = {}; + const containerMetadata = new Map(); - if (isDocker) containerMetadata.runtime = 'docker'; - if (isKubernetes) containerMetadata.orchestrator = 'kubernetes'; + if (isDocker) containerMetadata.set('runtime', 'docker'); + if (isKubernetes) containerMetadata.set('orchestrator', 'kubernetes'); return containerMetadata; } -/** - * @internal - * Attempt to add new env container metadata, but keep old data if it does not fit. - */ -async function addContainerMetadata(originalMetadata: ClientMetadata): Promise { - return extendEnvMetadata(originalMetadata, 'container', await getContainerMetadata()); -} - -/** - * @internal - * The `env` key to extend, paired with the only value type valid for that key. - */ -type EnvMetadataEntry = ['container', ContainerMetadata] | ['agent', string]; - -/** - * @internal - * Re-add each metadata value. - * Attempt to add `env[metadataKey]`, but keep old data if it does not fit. - */ -export function extendEnvMetadata( - originalMetadata: ClientMetadata, - ...[metadataKey, metadataValue]: EnvMetadataEntry -): ClientMetadata { - const isEmpty = - typeof metadataValue === 'string' - ? metadataValue.length === 0 - : Object.keys(metadataValue).length === 0; - if (isEmpty) return originalMetadata; - - const extendedMetadata = new LimitedSizeDocument(512); - - const extendedEnvMetadata: NonNullable = { - ...originalMetadata?.env, - [metadataKey]: metadataValue - }; - - for (const [key, val] of Object.entries(originalMetadata)) { - if (key !== 'env') { - extendedMetadata.ifItFitsItSits(key, val); - } else { - if (!extendedMetadata.ifItFitsItSits('env', extendedEnvMetadata)) { - // add in old data if newer / extended metadata does not fit - extendedMetadata.ifItFitsItSits('env', val); - } - } - } - - if (!('env' in originalMetadata)) { - extendedMetadata.ifItFitsItSits('env', extendedEnvMetadata); - } - - return extendedMetadata.toObject() as ClientMetadata; -} - /** * @internal * Environment variables that indicate the driver is being used by an AI agent, in the order the * spec requires them to be evaluated. [0] is the environment variable, [1] is the value to set - * when that environment variable is encountered. If [1] is null, use the (trimmed) environment variable value. + * when that environment variable is encountered. If [1] is null, use the environment variable value. * * From the spec: * client.env.agent is a single string. Its value is determined by the environment variables below. @@ -281,14 +236,6 @@ const AGENT_ENV_VARIABLES: ReadonlyArray = [ ['OPENCODE_CLIENT', 'opencode'] ]; -/** - * @internal - * Attempt to add new env agent metadata, but keep old data if it does not fit. - */ -function addAgentMetadata(originalMetadata: ClientMetadata): ClientMetadata { - return extendEnvMetadata(originalMetadata, 'agent', getAgentEnv()); -} - /** * @internal * Resolves `env.agent` from the environment, or an empty string when no agent variable is @@ -312,7 +259,7 @@ export function getAgentEnv(): string { * Collects FaaS metadata. * - `name` MUST be the last key in the Map returned. */ -export function getFAASEnv(): Map | null { +export function getFAASEnv(): Map { const { AWS_EXECUTION_ENV = '', AWS_LAMBDA_RUNTIME_API = '', @@ -385,7 +332,7 @@ export function getFAASEnv(): Map | null { return faasEnv; } - return null; + return faasEnv; } /** diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 96fcfc74d4..43efe27b72 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -7,8 +7,6 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { - type ClientMetadata, - extendEnvMetadata, getAgentEnv, getFAASEnv, LimitedSizeDocument, @@ -67,8 +65,8 @@ describe('client metadata module', () => { after(() => { delete process.env[envVariable]; }); - it('returns null', () => { - expect(getFAASEnv()).to.be.null; + it('returns an empty map', () => { + expect(getFAASEnv()).to.have.property('size', 0); }); }); }); @@ -93,14 +91,14 @@ describe('client metadata module', () => { after(() => { delete process.env.AWS_EXECUTION_ENV; }); - it('returns null', () => { - expect(getFAASEnv()).to.be.null; + it('returns an empty map', () => { + expect(getFAASEnv()).to.have.property('size', 0); }); }); context('when there is no FAAS provider data in the env', () => { - it('returns null', () => { - expect(getFAASEnv()).to.be.null; + it('returns an empty map', () => { + expect(getFAASEnv()).to.have.property('size', 0); }); }); @@ -116,8 +114,8 @@ describe('client metadata module', () => { delete process.env.AWS_EXECUTION_ENV; delete process.env.FUNCTIONS_WORKER_RUNTIME; }); - it('returns null', () => { - expect(getFAASEnv()).to.be.null; + it('returns an empty map', () => { + expect(getFAASEnv()).to.have.property('size', 0); }); }); @@ -625,6 +623,21 @@ describe('client metadata module', () => { expect(metadata).to.not.have.property('env'); }); }); + + context('when the faas env is too large and an agent is set', () => { + beforeEach('1. Omit fields from `env` except `env.name` & `env.agent`.', () => { + sinon.stub(process, 'env').get(() => ({ + AWS_EXECUTION_ENV: 'AWS_Lambda_iLoveJavaScript', + AWS_REGION: 'a'.repeat(512), + CLAUDECODE: '1' + })); + }); + + it('keeps env.name and env.agent', async () => { + const metadata = await makeClientMetadata([], { runtime }); + expect(metadata.env).to.deep.equal({ name: 'aws.lambda', agent: 'claude-code' }); + }); + }); }); describe('getAgentEnv()', function () { @@ -675,61 +688,4 @@ describe('client metadata module', () => { }); } }); - - describe('extendEnvMetadata()', function () { - const metadata: ClientMetadata = { - driver: { name: 'nodejs', version: NODE_DRIVER_VERSION }, - os: { type: 'Linux' }, - platform: 'Node.js v20.0.0, LE' - }; - - // 'If none of the variables above are populated, client.env.agent MUST be entirely omitted.' - context('when the value is empty', function () { - it('returns the metadata unchanged for a string value', function () { - expect(extendEnvMetadata(metadata, 'agent', '')).to.deep.equal(metadata); - }); - - it('returns the metadata unchanged for a document value', function () { - expect(extendEnvMetadata(metadata, 'container', {})).to.deep.equal(metadata); - }); - }); - - context('when the metadata has no env document', function () { - it('adds the env document and leaves the other fields untouched', function () { - expect(extendEnvMetadata(metadata, 'agent', 'custom-agent')).to.deep.equal({ - ...metadata, - env: { agent: 'custom-agent' } - }); - }); - }); - - context('when the metadata has an existing env document', function () { - it('merges the new key into the existing env document', function () { - const withAgent: ClientMetadata = { ...metadata, env: { agent: 'custom-agent' } }; - expect(extendEnvMetadata(withAgent, 'container', { runtime: 'docker' })).to.deep.equal({ - ...metadata, - env: { agent: 'custom-agent', container: { runtime: 'docker' } } - }); - }); - }); - - context('when the new value does not fit and there is an existing env document', function () { - it('keeps the original env document', function () { - const withEnv: ClientMetadata = { - ...metadata, - env: { name: 'aws.lambda', region: 'us-east-2' } - }; - expect(extendEnvMetadata(withEnv, 'agent', 'a'.repeat(512)).env).to.deep.equal({ - name: 'aws.lambda', - region: 'us-east-2' - }); - }); - }); - - context('when the new value does not fit and there is no existing env document', function () { - it('omits the env document entirely', function () { - expect(extendEnvMetadata(metadata, 'agent', 'a'.repeat(512))).to.not.have.property('env'); - }); - }); - }); }); From eb948eb920ea120f45dc1b99b79edce8bcd990a0 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 14 Sep 2026 17:59:02 -0400 Subject: [PATCH 07/45] fix: bad usage of FAAS in test --- src/sdam/monitor.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sdam/monitor.ts b/src/sdam/monitor.ts index e5b4a32a84..c6a4480e96 100644 --- a/src/sdam/monitor.ts +++ b/src/sdam/monitor.ts @@ -120,7 +120,7 @@ export class Monitor extends TypedEventEmitter { minHeartbeatFrequencyMS: options.minHeartbeatFrequencyMS ?? 500, serverMonitoringMode: options.serverMonitoringMode }); - this.isRunningInFaasEnv = getFAASEnv() != null; + this.isRunningInFaasEnv = getFAASEnv().size > 0; this.mongoLogger = this.server.topology.client?.mongoLogger; this.rttSampler = new RTTSampler(10); From b1e810b14ee9e3cc3cf3a1f66006a68a8efdb6b4 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Tue, 15 Sep 2026 18:24:24 -0400 Subject: [PATCH 08/45] test: explicit tests, fix up existing truncation tests --- .../cmap/handshake/client_metadata.test.ts | 95 +++++++++++-------- 1 file changed, 56 insertions(+), 39 deletions(-) diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 43efe27b72..9a14c08e34 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -559,19 +559,19 @@ describe('client metadata module', () => { }); describe('metadata truncation', function () { - context('when faas region is too large', () => { - beforeEach('1. Omit fields from `env` except `env.name`.', () => { + context('when the env document is too large', () => { + beforeEach('1. Omit fields from `env` except `env.name` & `env.agent`.', () => { sinon.stub(process, 'env').get(() => ({ + KUBERNETES_SERVICE_HOST: 'non_empty_string', AWS_EXECUTION_ENV: 'AWS_Lambda_iLoveJavaScript', - AWS_REGION: 'a'.repeat(512) + AWS_REGION: 'a'.repeat(512), + CLAUDECODE: '1' })); }); - it('only includes env.name', async () => { + it('omits container and faas fields, keeping env.name and env.agent', async () => { const metadata = await makeClientMetadata([], { runtime }); - expect(metadata).to.not.have.nested.property('env.region'); - expect(metadata).to.have.nested.property('env.name', 'aws.lambda'); - expect(metadata.env).to.have.all.keys('name'); + expect(metadata.env).to.deep.equal({ name: 'aws.lambda', agent: 'claude-code' }); }); }); @@ -585,7 +585,7 @@ describe('client metadata module', () => { sinon.stub(os, 'release').returns('a'.repeat(512)); }); - it('only includes env.name', async () => { + it('only includes os.type', async () => { const metadata = await makeClientMetadata([], { runtime }); expect(metadata).to.have.property('env'); expect(metadata).to.have.nested.property('env.region', 'abc'); @@ -609,35 +609,23 @@ describe('client metadata module', () => { }); }); - context('when there is no space for FaaS env', () => { + context('when there is no space for any env field', () => { beforeEach('3. Omit the `env` document entirely.', () => { sinon.stub(process, 'env').get(() => ({ + KUBERNETES_SERVICE_HOST: 'non_empty_string', AWS_EXECUTION_ENV: 'iLoveJavaScript', - AWS_REGION: 'abc' + AWS_LAMBDA_RUNTIME_API: 'non_empty_string', + AWS_REGION: 'abc', + CLAUDECODE: '1' })); sinon.stub(os, 'type').returns('a'.repeat(50)); }); - it('omits the faas env', async () => { + it('omits the env document', async () => { const metadata = await makeClientMetadata([{ name: 'a'.repeat(350) }], { runtime }); expect(metadata).to.not.have.property('env'); }); }); - - context('when the faas env is too large and an agent is set', () => { - beforeEach('1. Omit fields from `env` except `env.name` & `env.agent`.', () => { - sinon.stub(process, 'env').get(() => ({ - AWS_EXECUTION_ENV: 'AWS_Lambda_iLoveJavaScript', - AWS_REGION: 'a'.repeat(512), - CLAUDECODE: '1' - })); - }); - - it('keeps env.name and env.agent', async () => { - const metadata = await makeClientMetadata([], { runtime }); - expect(metadata.env).to.deep.equal({ name: 'aws.lambda', agent: 'claude-code' }); - }); - }); }); describe('getAgentEnv()', function () { @@ -665,27 +653,56 @@ describe('client metadata module', () => { // 'A variable is considered populated if it is present in the environment with a non-empty // value.' & 'The first populated variable determines the value, and subsequent entries MUST NOT be considered.' - const unpopulated: Array = ['', ' ', undefined]; + context('when an agent variable is set to a whitespace-only string', function () { + context('when the variable is a generic', function () { + stubEnv({ AI_AGENT: ' ' }); - for (const value of unpopulated) { - // A generic and a literal - for (const key of ['AI_AGENT', 'CLAUDECODE']) { - context(`when ${key} is set to "${value}"`, function () { - stubEnv({ [key]: value }); + it('treats the variable as unpopulated', function () { + expect(getAgentEnv()).to.equal(''); + }); + }); - it('treats the variable as unpopulated', function () { - expect(getAgentEnv()).to.equal(''); - }); + context('when the variable is a literal', function () { + stubEnv({ CLAUDECODE: ' ' }); + + it('treats the variable as unpopulated', function () { + expect(getAgentEnv()).to.equal(''); }); - } + }); - context(`when an earlier variable is set to "${value}"`, function () { - stubEnv({ AI_AGENT: value, CLAUDECODE: '1' }); + context('when the subject is an earlier variable', function () { + stubEnv({ AI_AGENT: ' ', CLAUDECODE: '1' }); it('skips it and considers the next variable', function () { expect(getAgentEnv()).to.equal('claude-code'); }); }); - } + }); + + context('when an agent variable is set to undefined', function () { + context('when the variable is a generic', function () { + stubEnv({ AI_AGENT: undefined }); + + it('treats the variable as unpopulated', function () { + expect(getAgentEnv()).to.equal(''); + }); + }); + + context('when the variable is a literal', function () { + stubEnv({ CLAUDECODE: undefined }); + + it('treats the variable as unpopulated', function () { + expect(getAgentEnv()).to.equal(''); + }); + }); + + context('when the subject is an earlier variable', function () { + stubEnv({ AI_AGENT: undefined, CLAUDECODE: '1' }); + + it('skips it and considers the next variable', function () { + expect(getAgentEnv()).to.equal('claude-code'); + }); + }); + }); }); }); From e177ff0b99380fe2a6334a9ba61e56a76ebb2575 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 16 Sep 2026 15:59:47 -0400 Subject: [PATCH 09/45] chore: address comment https://github.com/mongodb/node-mongodb-native/pull/5052#discussion_r4020599050 --- .../mongodb-handshake/mongodb-handshake.prose.test.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 97c2f401ec..02de6746df 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -23,7 +23,6 @@ function stubEnv(env: EnvironmentVariables) { before(function () { cachedEnv = process.env; process.env = { - ...process.env, ...Object.fromEntries(env) }; }); From c4e47932416d9871b8ee13241f344ef4d47b73f3 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 16 Sep 2026 19:43:40 -0400 Subject: [PATCH 10/45] chore: address comment https://github.com/mongodb/node-mongodb-native/pull/5052#discussion_r4020629903 --- src/cmap/handshake/client_metadata.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 1dcd35f757..be0db82807 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -182,9 +182,9 @@ export async function makeClientMetadata( const agentEnv = getAgentEnv(); const fullEnv = new Map(); - if (containerMetadata.size > 0) fullEnv.set('container', containerMetadata); for (const [k, v] of faasEnv) fullEnv.set(k, v); if (agentEnv.length > 0) fullEnv.set('agent', agentEnv); + if (containerMetadata.size > 0) fullEnv.set('container', containerMetadata); if (fullEnv.size > 0 && !metadataDocument.ifItFitsItSits('env', fullEnv)) { for (const key of fullEnv.keys()) { From 1625598714aab9cda9d9966ff5d1f8ff0797f56e Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 16 Sep 2026 19:46:22 -0400 Subject: [PATCH 11/45] chore: address comment https://github.com/mongodb/node-mongodb-native/pull/5052#discussion_r4020645700 --- test/mongodb_bundled.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/mongodb_bundled.ts b/test/mongodb_bundled.ts index 307a9e015c..fe8f5e083d 100644 --- a/test/mongodb_bundled.ts +++ b/test/mongodb_bundled.ts @@ -142,6 +142,7 @@ export const { gcpCallback, getAwsCredentialProvider, getFAASEnv, + getAgentEnv, getGcpMetadata, getMongoDBClientEncryption, GetMoreOperation, From b9f458250a646a1a8491d54eef290636639a3e0d Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 16 Sep 2026 19:48:35 -0400 Subject: [PATCH 12/45] test: make test not misleading --- test/unit/cmap/handshake/client_metadata.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 9a14c08e34..a3f16e7683 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -569,7 +569,7 @@ describe('client metadata module', () => { })); }); - it('omits container and faas fields, keeping env.name and env.agent', async () => { + it('faas fields, keeping env.name and env.agent', async () => { const metadata = await makeClientMetadata([], { runtime }); expect(metadata.env).to.deep.equal({ name: 'aws.lambda', agent: 'claude-code' }); }); From 3a4c7c45a5216a38d939381b7805b037bda47a40 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 17 Sep 2026 16:57:51 -0400 Subject: [PATCH 13/45] chore: address comment (r2) https://github.com/mongodb/node-mongodb-native/pull/5052#discussion_r4020599050 --- src/cmap/handshake/client_metadata.ts | 18 ++++++++++++++- .../mongodb-handshake.prose.test.ts | 12 ++++++++++ .../cmap/handshake/client_metadata.test.ts | 22 ++++++++++++++++++- 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index be0db82807..eca564b771 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -225,7 +225,7 @@ async function getContainerMetadata(): Promise> { * Drivers MUST evaluate the list in order. The first populated variable determines the value, and * subsequent entries MUST NOT be considered. */ -const AGENT_ENV_VARIABLES: ReadonlyArray = [ +export const AGENT_ENV_VARIABLES: ReadonlyArray = [ ['AI_AGENT', null], ['AGENT', null], ['CLAUDECODE', 'claude-code'], @@ -255,6 +255,22 @@ export function getAgentEnv(): string { return ''; } +export const FAAS_ENV_VARIABLES = [ + 'AWS_EXECUTION_ENV', + 'AWS_LAMBDA_RUNTIME_API', + 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', + 'AWS_REGION', + 'FUNCTIONS_WORKER_RUNTIME', + 'K_SERVICE', + 'FUNCTION_NAME', + 'FUNCTION_MEMORY_MB', + 'FUNCTION_REGION', + 'FUNCTION_TIMEOUT_SEC', + 'VERCEL', + 'VERCEL_REGION', + 'KUBERNETES_SERVICE_HOST' +] as const; + /** * Collects FaaS metadata. * - `name` MUST be the last key in the Map returned. diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 02de6746df..16695a7577 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -3,10 +3,12 @@ import * as process from 'process'; import * as sinon from 'sinon'; import { + AGENT_ENV_VARIABLES, type ClientMetadata, Connection, type Document, type DriverInfo, + FAAS_ENV_VARIABLES, getFAASEnv, type HandshakeDocument, Int32, @@ -18,11 +20,21 @@ import { sleep } from '../../tools/utils'; type EnvironmentVariables = Array<[string, string]>; +const handshakeEnvVars: string[] = [ + ...FAAS_ENV_VARIABLES, + ...AGENT_ENV_VARIABLES.map(([key]) => key) +]; + function stubEnv(env: EnvironmentVariables) { let cachedEnv: NodeJS.ProcessEnv; before(function () { cachedEnv = process.env; + + const cleanedEnv = { ...cachedEnv }; + for (const key of handshakeEnvVars) delete cleanedEnv[key]; + process.env = { + ...cleanedEnv, ...Object.fromEntries(env) }; }); diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index a3f16e7683..f48ae1a776 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -7,6 +7,8 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { + AGENT_ENV_VARIABLES, + FAAS_ENV_VARIABLES, getAgentEnv, getFAASEnv, LimitedSizeDocument, @@ -15,7 +17,26 @@ import { runNodelessTests } from '../../../mongodb'; import { runtime } from '../../../tools/utils'; + +const handshakeEnvVars: string[] = [ + ...FAAS_ENV_VARIABLES, + ...AGENT_ENV_VARIABLES.map(([key]) => key) +]; + describe('client metadata module', () => { + let cachedEnv: NodeJS.ProcessEnv; + + before(() => { + cachedEnv = process.env; + const cleanedEnv = { ...cachedEnv }; + for (const key of handshakeEnvVars) delete cleanedEnv[key]; + process.env = cleanedEnv; + }); + + after(() => { + process.env = cachedEnv; + }); + afterEach(() => sinon.restore()); describe('new LimitedSizeDocument()', () => { @@ -562,7 +583,6 @@ describe('client metadata module', () => { context('when the env document is too large', () => { beforeEach('1. Omit fields from `env` except `env.name` & `env.agent`.', () => { sinon.stub(process, 'env').get(() => ({ - KUBERNETES_SERVICE_HOST: 'non_empty_string', AWS_EXECUTION_ENV: 'AWS_Lambda_iLoveJavaScript', AWS_REGION: 'a'.repeat(512), CLAUDECODE: '1' From e6b640fe2cc128080cafee321e8a3f4a68412f1c Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 17 Sep 2026 17:02:00 -0400 Subject: [PATCH 14/45] chore: mark FAAS_ENV_VARIABLES as internal --- src/cmap/handshake/client_metadata.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index eca564b771..2c5f93bf25 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -255,6 +255,11 @@ export function getAgentEnv(): string { return ''; } +/** + * @internal + * Environment variables relevant to FaaS runtimes, governed by the spec: + * https://github.com/mongodb/specifications/blob/9cfe388c7d2ce1e02b24b53606e97ce7b73ebb7d/source/mongodb-handshake/handshake.md#faas + */ export const FAAS_ENV_VARIABLES = [ 'AWS_EXECUTION_ENV', 'AWS_LAMBDA_RUNTIME_API', From 3be0e2ecc63c2b42237f7c7504dd6bce6088ecdd Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:29:51 -0400 Subject: [PATCH 15/45] fix: retain old behaviour of append-after container --- src/cmap/handshake/client_metadata.ts | 17 +++++++++++++---- .../unit/cmap/handshake/client_metadata.test.ts | 9 +++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 2c5f93bf25..acb499936c 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -74,12 +74,19 @@ export class LimitedSizeDocument { // The BSON byteLength of the new element is the same as serializing it to its own document // subtracting the document size int32 and the null terminator. const newElementSize = BSON.serialize(new Map().set(key, value)).byteLength - 5; + + let baseDocumentSize = this.documentSize; + // If the incoming key is a replace op, don't double-count the size + if (this.document.has(key)) { + // new document size = current size - existing value, prepping for replacement + baseDocumentSize -= BSON.serialize(new Map().set(key, this.document.get(key))).byteLength - 5; + } - if (newElementSize + this.documentSize > this.maxSize) { + if (newElementSize + baseDocumentSize > this.maxSize) { return false; } - this.documentSize += newElementSize; + this.documentSize = baseDocumentSize + newElementSize; this.document.set(key, value); @@ -184,8 +191,6 @@ export async function makeClientMetadata( const fullEnv = new Map(); for (const [k, v] of faasEnv) fullEnv.set(k, v); if (agentEnv.length > 0) fullEnv.set('agent', agentEnv); - if (containerMetadata.size > 0) fullEnv.set('container', containerMetadata); - if (fullEnv.size > 0 && !metadataDocument.ifItFitsItSits('env', fullEnv)) { for (const key of fullEnv.keys()) { fullEnv.delete(key); @@ -193,6 +198,10 @@ export async function makeClientMetadata( if (metadataDocument.ifItFitsItSits('env', fullEnv)) break; } } + if (containerMetadata.size > 0) { + const newEnv = { ...Object.fromEntries(fullEnv), 'container': containerMetadata }; + metadataDocument.ifItFitsItSits('env', newEnv) + } return metadataDocument.toObject() as ClientMetadata; } diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index f48ae1a776..28967af73a 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -57,6 +57,15 @@ describe('client metadata module', () => { expect(doc.ifItFitsItSits('_id2', '')).to.be.false; expect(doc.toObject()).to.have.all.keys('_id'); }); + + it('does not double-count incoming value sizes into the document', () => { + const doc = new LimitedSizeDocument(22); + // A replacement op with the same byte length does not exceed the size limit + expect(doc.ifItFitsItSits('_id', new ObjectId())).to.be.true; + expect(doc.ifItFitsItSits('_id', new ObjectId())).to.be.true; + // But a new op does + expect(doc.ifItFitsItSits('_id2', new ObjectId())).to.be.false; + }); }); describe('getFAASEnv()', function () { From 32bade6b0ed13e902dcc74a34bcbf44c6b6d4d10 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:37:57 -0400 Subject: [PATCH 16/45] chore: lint --- src/cmap/handshake/client_metadata.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index acb499936c..06ae84010e 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -74,7 +74,7 @@ export class LimitedSizeDocument { // The BSON byteLength of the new element is the same as serializing it to its own document // subtracting the document size int32 and the null terminator. const newElementSize = BSON.serialize(new Map().set(key, value)).byteLength - 5; - + let baseDocumentSize = this.documentSize; // If the incoming key is a replace op, don't double-count the size if (this.document.has(key)) { @@ -199,8 +199,8 @@ export async function makeClientMetadata( } } if (containerMetadata.size > 0) { - const newEnv = { ...Object.fromEntries(fullEnv), 'container': containerMetadata }; - metadataDocument.ifItFitsItSits('env', newEnv) + const newEnv = { ...Object.fromEntries(fullEnv), container: containerMetadata }; + metadataDocument.ifItFitsItSits('env', newEnv); } return metadataDocument.toObject() as ClientMetadata; From 6af2243c87bbd2b19d50976bb11354f60983aa7d Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 21 Sep 2026 13:12:33 -0400 Subject: [PATCH 17/45] fix: missing bundled exports --- test/mongodb_bundled.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/mongodb_bundled.ts b/test/mongodb_bundled.ts index fe8f5e083d..7fea749d02 100644 --- a/test/mongodb_bundled.ts +++ b/test/mongodb_bundled.ts @@ -145,6 +145,8 @@ export const { getAgentEnv, getGcpMetadata, getMongoDBClientEncryption, + AGENT_ENV_VARIABLES, + FAAS_ENV_VARIABLES, GetMoreOperation, getTopology, GridFSBucket, From 320b620aa1c0f02d07d8df4c633b942107376df6 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Tue, 22 Sep 2026 17:40:59 -0400 Subject: [PATCH 18/45] feat: add normalization, fix tests --- src/cmap/handshake/client_metadata.ts | 41 ++++++-- .../mongodb-handshake.prose.test.ts | 72 ++++++++++---- test/mongodb_bundled.ts | 2 + .../cmap/handshake/client_metadata.test.ts | 96 +++++++++++-------- 4 files changed, 140 insertions(+), 71 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 06ae84010e..ce2a48bc9b 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -235,29 +235,50 @@ async function getContainerMetadata(): Promise> { * subsequent entries MUST NOT be considered. */ export const AGENT_ENV_VARIABLES: ReadonlyArray = [ - ['AI_AGENT', null], - ['AGENT', null], ['CLAUDECODE', 'claude-code'], + ['CLAUDE_CODE_ENTRYPOINT', 'claude_code'], ['CURSOR_AGENT', 'cursor'], - ['GEMINI_CLI', 'gemini-cli'], ['CODEX_SANDBOX', 'codex'], - ['AUGMENT_AGENT', 'augment'], - ['OPENCODE_CLIENT', 'opencode'] + ['CLINE_ACTIVE', 'cline'], + ['GEMINI_CLI', 'gemini_cli'], + ['AUGMENT_AGENT', 'auggie_cli'], + ['OPENCODE_CLIENT', 'opencode_client'], + ['TRAE_AI_SHELL_ID', 'trae_ai'], + ['GOOSE_TERMINAL', 'goose'], + ['GOOSE_AGENT', 'goose'], + ['AI_AGENT', null] ]; +/** + * @internal + * Env var value length after first 2 forms of normalization + */ +export const AGENT_ENV_LIMIT = 64; +/** + * @internal + * Values used in AI_AGENT to indicate an agent is being used but are non-identifying + */ +export const AGENT_ENV_UNIDENTIFYING = new Set(['1', 'true']) /** * @internal * Resolves `env.agent` from the environment, or an empty string when no agent variable is * populated. Returns the value of the first populated variable in `AGENT_ENV_VARIABLES`. */ export function getAgentEnv(): string { + for (const [key, literal] of AGENT_ENV_VARIABLES) { - // A variable is only populated if it is present with a non-empty value, so an empty or + // A variable is only populated if it is present with a non-empty normalized value, so an empty or // whitespace-only value never selects an entry, even one with a fixed table value. - // A populated value is reported verbatim; only the populated check ignores whitespace. - const envValue = process.env[key] ?? ''; - if (envValue.trim().length > 0) { - return literal ?? envValue; + const envValue = (process.env[key] ?? '') + .trim() + .toLowerCase() + .substring(0, AGENT_ENV_LIMIT); + + if (envValue.length > 0) { + if (!literal) { + return AGENT_ENV_UNIDENTIFYING.has(envValue) ? 'ai_agent' : envValue; + } + return literal; } } diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 16695a7577..ac7e62b73a 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -221,58 +221,92 @@ describe('Handshake Prose Tests', function () { expectEnv: object; env?: EnvironmentVariables; }> = [ - // 1. Generic agent via AI_AGENT. client.env.agent MUST equal custom-agent. + // 1. Known agent. client.env.agent MUST equal claude-code. { - env: [['AI_AGENT', 'custom-agent']], + env: [['CLAUDECODE', '1']], expectEnv: { - agent: 'custom-agent' + agent: 'claude-code' } }, - // 2. Generic agent via AGENT. client.env.agent MUST equal custom-agent. + // 2. Known agent, fixed name. client.env.agent MUST equal 'cursor', regardless of the value of the enviornment variable. { - env: [['AGENT', 'custom-agent']], + env: [['CURSOR_AGENT', 'some-value-42']], expectEnv: { - agent: 'custom-agent' + agent: 'cursor' } }, - // 3. Known agent. client.env.agent MUST equal claude-code. + // 3. Precedence - first known agent wins. `client.env.agent` MUST equal `cursor`, not `gemini_cli`. { - env: [['CLAUDECODE', '1']], + env: [ + ['CURSOR_AGENT', '1'], + ['GEMINI_CLI', '1'] + ], expectEnv: { - agent: 'claude-code' + agent: 'cursor' } }, - // 4. Precedence - generic wins over known. client.env.agent MUST equal custom-agent (the value of AI_AGENT), not claude-code. + // 4. Precedence - a known agent wins over the generic variable. `client.env.agent` MUST equal `claude_code`, not + // `custom-agent`. { env: [ ['AI_AGENT', 'custom-agent'], ['CLAUDECODE', '1'] ], + expectEnv: { + agent: 'cursor' + } + }, + // 5. Generic agent with a descriptive value. `client.env.agent` MUST equal `custom-agent`. + { + env: [['AI_AGENT', 'custom-agent']], expectEnv: { agent: 'custom-agent' } }, - // 5. Precedence - first known wins. client.env.agent MUST equal cursor. + // 6. Generic agent with a boolean value. `client.env.agent` MUST equal `ai_agent`. { - env: [ - ['CURSOR_AGENT', '1'], - ['GEMINI_CLI', '1'] - ], + env: [['AI_AGENT', '-agent']], expectEnv: { - agent: 'cursor' + agent: 'custom-agent' + } + }, + // 7. Generic agent, normalization. `AI_AGENT` is set to `Claude-Code_2-1-238_Agent` with one leading space and one + // trailing space. The value is converted to lowercase and leading and trailing whitespace is removed, so + // `client.env.agent` MUST equal `claude-code_2-1-238_agent`. + { + env: [['AI_AGENT', ' Claude-Code_2-1-238_Agent ']], + expectEnv: { + agent: 'claude-code_2-1-238_agent' } }, - // 6. Empty value is treated as unset. client.env.agent MUST be omitted. If no other client.env fields are populated, client.env MUST be entirely omitted. + // 8. Generic agent, truncation. `AI_AGENT` is set to a value of 100 characters. `client.env.agent` MUST equal the first + // 64 characters of that value. + { + env: [['AI_AGENT', 'a'.repeat(100)]], + expectEnv: { + agent: 'a'.repeat(64), + } + }, + // 9. Empty value is treated as unset. `AI_AGENT` is set to an empty string. `client.env.agent` MUST be omitted. If no + // other `client.env` fields are populated, `client.env` MUST be entirely omitted. { env: [['AI_AGENT', '']], expectEnv: undefined }, - // 7. No agent variables. None of the environment variables in the client.env.agent table are set. client.env.agent MUST be omitted. + // 10. Whitespace-only value is treated as unset. `AI_AGENT` is set to `" "` (three space characters). `client.env.agent` + // MUST be omitted. + { + env: [['AI_AGENT', ' ']], + expectEnv: undefined + }, + // 11. No agent variables. None of the environment variables in the `client.env.agent` table are set. `client.env.agent` + // MUST be omitted. { env: [], expectEnv: undefined }, - // 8. Agent alongside FaaS. This test MUST verify that both the AWS Lambda metadata and client.env.agent (equal to claude-code) are present in client.env. + // 12. Agent alongside FaaS. This test MUST verify that both the AWS Lambda metadata and `client.env.agent` (equal to + // `claude_code`) are present in `client.env`. { env: [ ['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'], diff --git a/test/mongodb_bundled.ts b/test/mongodb_bundled.ts index 7fea749d02..c598a53377 100644 --- a/test/mongodb_bundled.ts +++ b/test/mongodb_bundled.ts @@ -146,6 +146,8 @@ export const { getGcpMetadata, getMongoDBClientEncryption, AGENT_ENV_VARIABLES, + AGENT_ENV_LIMIT, + AGENT_ENV_UNIDENTIFYING, FAAS_ENV_VARIABLES, GetMoreOperation, getTopology, diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 28967af73a..d1f3dfd3ba 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -8,6 +8,8 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { AGENT_ENV_VARIABLES, + AGENT_ENV_LIMIT, + AGENT_ENV_UNIDENTIFYING, FAAS_ENV_VARIABLES, getAgentEnv, getFAASEnv, @@ -659,74 +661,84 @@ describe('client metadata module', () => { describe('getAgentEnv()', function () { const stubEnv = (env: NodeJS.ProcessEnv) => { - beforeEach(function () { - sinon.stub(process, 'env').get(() => env); + sinon.stub(process, 'env').get(() => env); + } + const stubEnvBefore = (env: NodeJS.ProcessEnv) => { + beforeEach(function() { + stubEnv(env); }); }; - context('when a fixed-value agent variable is set to an arbitrary value', function () { - stubEnv({ GEMINI_CLI: 'some-other-value' }); - + context('when a fixed-value is used', function () { + stubEnvBefore({ GEMINI_CLI: 'some-other-value' }); it('returns the value from the agent table, not the environment', function () { - expect(getAgentEnv()).to.equal('gemini-cli'); - }); - }); - - context('when a generic agent variable is padded with whitespace', function () { - stubEnv({ AI_AGENT: ' custom-agent ' }); - - it('returns the value verbatim', function () { - expect(getAgentEnv()).to.equal(' custom-agent '); + expect(getAgentEnv()).to.equal('gemini_cli'); }); - }); - - // 'A variable is considered populated if it is present in the environment with a non-empty - // value.' & 'The first populated variable determines the value, and subsequent entries MUST NOT be considered.' - context('when an agent variable is set to a whitespace-only string', function () { - context('when the variable is a generic', function () { - stubEnv({ AI_AGENT: ' ' }); - - it('treats the variable as unpopulated', function () { + context('and normalization results in an empty value', function () { + stubEnvBefore({ GEMINI_CLI: ` ` }); + it('it skips literals', function () { expect(getAgentEnv()).to.equal(''); }); - }); - - context('when the variable is a literal', function () { - stubEnv({ CLAUDECODE: ' ' }); + }) + }); - it('treats the variable as unpopulated', function () { - expect(getAgentEnv()).to.equal(''); + context('when a generic agent variable is used', function () { + context('and the value is already normalized', function () { + stubEnvBefore({ AI_AGENT: 'custom-agent' }); + it('returns the provided value', function () { + expect(getAgentEnv()).to.equal('custom-agent'); }); }); - context('when the subject is an earlier variable', function () { - stubEnv({ AI_AGENT: ' ', CLAUDECODE: '1' }); - - it('skips it and considers the next variable', function () { - expect(getAgentEnv()).to.equal('claude-code'); + context('and the value needs to be normalized', function () { + it('whitespace is stripped', function () { + stubEnv({ AI_AGENT: ' custom-agent ' }); + expect(getAgentEnv()).to.equal('custom-agent'); + }); + it('ucase is flipped', function () { + stubEnv({ AI_AGENT: 'cUsToM-aGeNt' }); + expect(getAgentEnv()).to.equal('custom-agent'); }); + it('truncation is tripped', function () { + stubEnv({ AI_AGENT: 'a'.repeat(100) }); + expect(getAgentEnv()).to.equal('a'.repeat(AGENT_ENV_LIMIT)); + }); + }) + + context('and the normalized value resolves to a non-identfying presence', function () { + Array.from(AGENT_ENV_UNIDENTIFYING).forEach((val) => { + it(`should map '${val}' to 'ai-agent'`, function () { + stubEnv({ AI_AGENT: val }); + expect(getAgentEnv()).to.equal('ai_agent'); + }) + }) }); + + context('and normalization results in an empty value', function () { + stubEnvBefore({ AI_AGENT: ' ' }); + it('skips fixed values', function () { + expect(getAgentEnv()).to.equal(''); + }); + }) }); context('when an agent variable is set to undefined', function () { - context('when the variable is a generic', function () { - stubEnv({ AI_AGENT: undefined }); - + context('and the variable is a generic', function () { + stubEnvBefore({ AI_AGENT: undefined }); it('treats the variable as unpopulated', function () { expect(getAgentEnv()).to.equal(''); }); }); - context('when the variable is a literal', function () { - stubEnv({ CLAUDECODE: undefined }); - + context('and the variable is a literal', function () { + stubEnvBefore({ CLAUDECODE: undefined }); it('treats the variable as unpopulated', function () { expect(getAgentEnv()).to.equal(''); }); }); - context('when the subject is an earlier variable', function () { - stubEnv({ AI_AGENT: undefined, CLAUDECODE: '1' }); + context('and the subject is an earlier variable', function () { + stubEnvBefore({ AI_AGENT: undefined, CLAUDECODE: '1' }); it('skips it and considers the next variable', function () { expect(getAgentEnv()).to.equal('claude-code'); From 2aebac17977944338e22b20d23fc483d22559465 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:29:34 -0400 Subject: [PATCH 19/45] chore: lint --- src/cmap/handshake/client_metadata.ts | 10 +++------- .../mongodb-handshake.prose.test.ts | 2 +- .../cmap/handshake/client_metadata.test.ts | 20 +++++++++---------- 3 files changed, 14 insertions(+), 18 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index ce2a48bc9b..343262b92f 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -239,7 +239,7 @@ export const AGENT_ENV_VARIABLES: ReadonlyArray 0) { if (!literal) { diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index ac7e62b73a..84fee5528d 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -284,7 +284,7 @@ describe('Handshake Prose Tests', function () { { env: [['AI_AGENT', 'a'.repeat(100)]], expectEnv: { - agent: 'a'.repeat(64), + agent: 'a'.repeat(64) } }, // 9. Empty value is treated as unset. `AI_AGENT` is set to an empty string. `client.env.agent` MUST be omitted. If no diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index d1f3dfd3ba..6e1314d803 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -7,9 +7,9 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { - AGENT_ENV_VARIABLES, AGENT_ENV_LIMIT, AGENT_ENV_UNIDENTIFYING, + AGENT_ENV_VARIABLES, FAAS_ENV_VARIABLES, getAgentEnv, getFAASEnv, @@ -662,9 +662,9 @@ describe('client metadata module', () => { describe('getAgentEnv()', function () { const stubEnv = (env: NodeJS.ProcessEnv) => { sinon.stub(process, 'env').get(() => env); - } + }; const stubEnvBefore = (env: NodeJS.ProcessEnv) => { - beforeEach(function() { + beforeEach(function () { stubEnv(env); }); }; @@ -679,7 +679,7 @@ describe('client metadata module', () => { it('it skips literals', function () { expect(getAgentEnv()).to.equal(''); }); - }) + }); }); context('when a generic agent variable is used', function () { @@ -703,23 +703,23 @@ describe('client metadata module', () => { stubEnv({ AI_AGENT: 'a'.repeat(100) }); expect(getAgentEnv()).to.equal('a'.repeat(AGENT_ENV_LIMIT)); }); - }) + }); context('and the normalized value resolves to a non-identfying presence', function () { - Array.from(AGENT_ENV_UNIDENTIFYING).forEach((val) => { + Array.from(AGENT_ENV_UNIDENTIFYING).forEach(val => { it(`should map '${val}' to 'ai-agent'`, function () { stubEnv({ AI_AGENT: val }); expect(getAgentEnv()).to.equal('ai_agent'); - }) - }) + }); + }); }); - + context('and normalization results in an empty value', function () { stubEnvBefore({ AI_AGENT: ' ' }); it('skips fixed values', function () { expect(getAgentEnv()).to.equal(''); }); - }) + }); }); context('when an agent variable is set to undefined', function () { From 752b9de1cd70f4ff9050198e46fd3a4c9a0e3f6a Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:50:14 -0400 Subject: [PATCH 20/45] fix: claude-code -> claude_code --- src/cmap/handshake/client_metadata.ts | 2 +- .../mongodb-handshake.prose.test.ts | 20 +++++++++---------- .../cmap/handshake/client_metadata.test.ts | 4 ++-- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 343262b92f..19896c3fd1 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -235,7 +235,7 @@ async function getContainerMetadata(): Promise> { * subsequent entries MUST NOT be considered. */ export const AGENT_ENV_VARIABLES: ReadonlyArray = [ - ['CLAUDECODE', 'claude-code'], + ['CLAUDECODE', 'claude_code'], ['CLAUDE_CODE_ENTRYPOINT', 'claude_code'], ['CURSOR_AGENT', 'cursor'], ['CODEX_SANDBOX', 'codex'], diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 84fee5528d..8984e28b22 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -221,11 +221,11 @@ describe('Handshake Prose Tests', function () { expectEnv: object; env?: EnvironmentVariables; }> = [ - // 1. Known agent. client.env.agent MUST equal claude-code. + // 1. Known agent. client.env.agent MUST equal claude_code. { env: [['CLAUDECODE', '1']], expectEnv: { - agent: 'claude-code' + agent: 'claude_code' } }, // 2. Known agent, fixed name. client.env.agent MUST equal 'cursor', regardless of the value of the enviornment variable. @@ -253,7 +253,7 @@ describe('Handshake Prose Tests', function () { ['CLAUDECODE', '1'] ], expectEnv: { - agent: 'cursor' + agent: 'claude_code' } }, // 5. Generic agent with a descriptive value. `client.env.agent` MUST equal `custom-agent`. @@ -265,18 +265,18 @@ describe('Handshake Prose Tests', function () { }, // 6. Generic agent with a boolean value. `client.env.agent` MUST equal `ai_agent`. { - env: [['AI_AGENT', '-agent']], + env: [['AI_AGENT', 'true']], expectEnv: { - agent: 'custom-agent' + agent: 'ai_agent' } }, - // 7. Generic agent, normalization. `AI_AGENT` is set to `Claude-Code_2-1-238_Agent` with one leading space and one + // 7. Generic agent, normalization. `AI_AGENT` is set to `claude_code_2-1-238_Agent` with one leading space and one // trailing space. The value is converted to lowercase and leading and trailing whitespace is removed, so - // `client.env.agent` MUST equal `claude-code_2-1-238_agent`. + // `client.env.agent` MUST equal `claude_code_2-1-238_agent`. { - env: [['AI_AGENT', ' Claude-Code_2-1-238_Agent ']], + env: [['AI_AGENT', ' claude_code_2-1-238_Agent ']], expectEnv: { - agent: 'claude-code_2-1-238_agent' + agent: 'claude_code_2-1-238_agent' } }, // 8. Generic agent, truncation. `AI_AGENT` is set to a value of 100 characters. `client.env.agent` MUST equal the first @@ -314,7 +314,7 @@ describe('Handshake Prose Tests', function () { ['CLAUDECODE', '1'] ], expectEnv: { - agent: 'claude-code', + agent: 'claude_code', region: 'us-east-2', name: 'aws.lambda' } diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 6e1314d803..b1e462b6de 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -602,7 +602,7 @@ describe('client metadata module', () => { it('faas fields, keeping env.name and env.agent', async () => { const metadata = await makeClientMetadata([], { runtime }); - expect(metadata.env).to.deep.equal({ name: 'aws.lambda', agent: 'claude-code' }); + expect(metadata.env).to.deep.equal({ name: 'aws.lambda', agent: 'claude_code' }); }); }); @@ -741,7 +741,7 @@ describe('client metadata module', () => { stubEnvBefore({ AI_AGENT: undefined, CLAUDECODE: '1' }); it('skips it and considers the next variable', function () { - expect(getAgentEnv()).to.equal('claude-code'); + expect(getAgentEnv()).to.equal('claude_code'); }); }); }); From b89eea7f64c0b87d01d5bec1654fd72ed88eab2c Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 30 Sep 2026 17:52:07 -0400 Subject: [PATCH 21/45] feat: support byte-truncation on strings --- src/cmap/handshake/client_metadata.ts | 19 ++--- src/utils.ts | 19 +++++ .../mongodb-handshake.prose.test.ts | 38 ++++++--- .../cmap/handshake/client_metadata.test.ts | 81 ++++++++++--------- test/unit/utils.test.ts | 34 ++++++++ 5 files changed, 135 insertions(+), 56 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 19896c3fd1..6c29b65297 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -1,9 +1,9 @@ import * as process from 'process'; -import { BSON, ByteUtils, type Document, Int32, NumberUtils } from '../../bson'; +import { BSON, type Document, Int32, NumberUtils } from '../../bson'; import { MongoInvalidArgumentError } from '../../error'; import type { DriverInfo, MongoOptions } from '../../mongo_client'; -import { fileIsAccessible } from '../../utils'; +import { DriverStringUtils, fileIsAccessible } from '../../utils'; // eslint-disable-next-line @typescript-eslint/no-require-imports const NODE_DRIVER_VERSION = require('../../../package.json').version; @@ -103,6 +103,8 @@ export class LimitedSizeDocument { } } +const APP_NAME_TRUNCATION_LIMIT_BYTES = 128; + type MakeClientMetadataOptions = Pick; /** @@ -122,10 +124,7 @@ export async function makeClientMetadata( // Add app name first, it must be sent if (appName.length > 0) { - const name = - ByteUtils.utf8ByteLength(appName) <= 128 - ? appName - : ByteUtils.toUTF8(ByteUtils.fromUTF8(appName), 0, 128, false); + const name = DriverStringUtils.truncateStringBytes(appName, APP_NAME_TRUNCATION_LIMIT_BYTES); metadataDocument.ifItFitsItSits('application', { name }); } @@ -238,7 +237,7 @@ export const AGENT_ENV_VARIABLES: ReadonlyArray 0) { + envValue = DriverStringUtils.truncateStringBytes(envValue, AGENT_ENV_LIMIT_BYTES); if (!literal) { return AGENT_ENV_UNIDENTIFYING.has(envValue) ? 'ai_agent' : envValue; } diff --git a/src/utils.ts b/src/utils.ts index d9a96115fc..89042f050d 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -3,6 +3,7 @@ import { type EventEmitter } from 'events'; import { promises as fs } from 'fs'; import * as http from 'http'; import * as process from 'process'; +import { StringDecoder } from 'string_decoder'; import { clearTimeout, setTimeout } from 'timers'; import { @@ -1143,6 +1144,24 @@ export function parseUnsignedInteger(value: unknown): number | null { return parsedInt != null && parsedInt >= 0 ? parsedInt : null; } +/** @internal */ +export const DriverStringUtils = { + /** + * Truncates a string to a specified byte length. Multi-byte characters which are bisected by the byte truncation + * are considered, ensuring incomplete multi-byte characters are omitted from the result entirely. + */ + truncateStringBytes(str: string, limit: number, encoding: BufferEncoding = 'utf8'): string { + if (!Number.isInteger(limit) || limit < 0) { + throw new Error('bad argument'); + } + const buf = Buffer.from(str, encoding); + if (buf.length <= limit) return str; + const decoder = new StringDecoder(encoding); + // incomplete multi-byte chars will not be returned through decoder.write + return decoder.write(buf.subarray(0, limit)); + } +}; + /** * This function throws a MongoAPIError in the event that either of the following is true: * * If the provided address domain does not match the provided parent domain diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 8984e28b22..bc56c5d824 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -270,16 +270,24 @@ describe('Handshake Prose Tests', function () { agent: 'ai_agent' } }, - // 7. Generic agent, normalization. `AI_AGENT` is set to `claude_code_2-1-238_Agent` with one leading space and one - // trailing space. The value is converted to lowercase and leading and trailing whitespace is removed, so - // `client.env.agent` MUST equal `claude_code_2-1-238_agent`. + // 7. Generic agent, boolean value with whitespace. `AI_AGENT` is set to `true` with one leading and one trailing space. + // The value is normalized before it is compared, so `client.env.agent` MUST equal `ai_agent`. + { + env: [['AI_AGENT', ' true ']], + expectEnv: { + agent: 'ai_agent' + } + }, + // 8. Generic agent, normalization. `AI_AGENT` is set to `Claude-Code_2-1-238_Agent` with one leading and one trailing + // space. `client.env.agent` MUST equal `claude-code_2-1-238_agent`. { env: [['AI_AGENT', ' claude_code_2-1-238_Agent ']], expectEnv: { agent: 'claude_code_2-1-238_agent' } }, - // 8. Generic agent, truncation. `AI_AGENT` is set to a value of 100 characters. `client.env.agent` MUST equal the first + + // 9. Generic agent, truncation. `AI_AGENT` is set to a value of 100 characters. `client.env.agent` MUST equal the first // 64 characters of that value. { env: [['AI_AGENT', 'a'.repeat(100)]], @@ -287,26 +295,36 @@ describe('Handshake Prose Tests', function () { agent: 'a'.repeat(64) } }, - // 9. Empty value is treated as unset. `AI_AGENT` is set to an empty string. `client.env.agent` MUST be omitted. If no - // other `client.env` fields are populated, `client.env` MUST be entirely omitted. + // 10. Generic agent, truncation on a character boundary. `AI_AGENT` is set to 63 `a` characters followed by `é` (U+00E9), + // two bytes in UTF-8. The 64-byte limit falls inside `é`, so `client.env.agent` MUST equal the 63 `a` characters. It + // MUST NOT contain any part of `é` or a replacement character (U+FFFD). + { + env: [['AI_AGENT', 'a'.repeat(63) + 'é']], + expectEnv: { + agent: 'a'.repeat(63) + } + }, + // 11. Empty value is unset. `AI_AGENT` is set to an empty string. `client.env.agent` MUST be omitted. If no other + //`client.env` fields are populated, `client.env` MUST be omitted entirely. { env: [['AI_AGENT', '']], expectEnv: undefined }, - // 10. Whitespace-only value is treated as unset. `AI_AGENT` is set to `" "` (three space characters). `client.env.agent` + + // 12. Whitespace-only value is treated as unset. `AI_AGENT` is set to `" "` (three space characters). `client.env.agent` // MUST be omitted. { env: [['AI_AGENT', ' ']], expectEnv: undefined }, - // 11. No agent variables. None of the environment variables in the `client.env.agent` table are set. `client.env.agent` + // 13. No agent variables. None of the environment variables in the `client.env.agent` table are set. `client.env.agent` // MUST be omitted. { env: [], expectEnv: undefined }, - // 12. Agent alongside FaaS. This test MUST verify that both the AWS Lambda metadata and `client.env.agent` (equal to - // `claude_code`) are present in `client.env`. + // 14. Agent alongside FaaS. This test MUST verify that the AWS Lambda metadata and `client.env.agent` (equal to + // `claude_code`) are both present in `client.env`. { env: [ ['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'], diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index b1e462b6de..42a4b80fe6 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -7,9 +7,10 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { - AGENT_ENV_LIMIT, + AGENT_ENV_LIMIT_BYTES, AGENT_ENV_UNIDENTIFYING, AGENT_ENV_VARIABLES, + DriverStringUtils, FAAS_ENV_VARIABLES, getAgentEnv, getFAASEnv, @@ -303,39 +304,11 @@ describe('client metadata module', () => { }); context('when app name is provided', () => { - context('when the app name is over 128 bytes', () => { - it('truncates the application name to <=128 bytes', async () => { - const longString = 'a'.repeat(300); - const metadata = await makeClientMetadata([], { - runtime, - appName: longString - }); - expect(metadata.application?.name).to.be.a('string'); - // the above assertion fails if `metadata.application?.name` is undefined, so - // we can safely assert that it exists - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - expect(Buffer.byteLength(metadata.application!.name, 'utf8')).to.equal(128); - }); - }); - - context( - 'TODO(NODE-5150): fix appName truncation when multi-byte unicode charaters straddle byte 128', - () => { - it('truncates the application name to 129 bytes', async () => { - const longString = '€'.repeat(300); - const metadata = await makeClientMetadata([], { - runtime, - appName: longString - }); - - expect(metadata.application?.name).to.be.a('string'); - // the above assertion fails if `metadata.application?.name` is undefined, so - // we can safely assert that it exists - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - expect(Buffer.byteLength(metadata.application!.name, 'utf8')).to.equal(129); - }); - } - ); + it('truncates the application name with truncateStringBytes', async () => { + const spy = sinon.spy(DriverStringUtils, 'truncateStringBytes'); + await makeClientMetadata([], { runtime, appName: 'myApplication' }); + expect(spy).to.have.been.calledOnceWithExactly('myApplication', 128); + }); context('when the app name is under 128 bytes', () => { it('sets the application name to the value', async () => { @@ -699,9 +672,11 @@ describe('client metadata module', () => { stubEnv({ AI_AGENT: 'cUsToM-aGeNt' }); expect(getAgentEnv()).to.equal('custom-agent'); }); - it('truncation is tripped', function () { - stubEnv({ AI_AGENT: 'a'.repeat(100) }); - expect(getAgentEnv()).to.equal('a'.repeat(AGENT_ENV_LIMIT)); + it('truncates the normalized value with truncateStringBytes', function () { + const spy = sinon.spy(DriverStringUtils, 'truncateStringBytes'); + stubEnv({ AI_AGENT: ' CUSTOM-AGENT ' }); + getAgentEnv(); + expect(spy).to.have.been.calledOnceWithExactly('custom-agent', AGENT_ENV_LIMIT_BYTES); }); }); @@ -745,5 +720,37 @@ describe('client metadata module', () => { }); }); }); + + context('each agent variable maps to its expected value', function () { + // Hardcoded copy of the spec's `client.env.agent` table. Intentionally not derived from + // AGENT_ENV_VARIABLES so that changes to the driver's table are caught here. + const agentTable: Array<{ variable: string; value: string; expected: string }> = [ + { variable: 'CLAUDECODE', value: '1', expected: 'claude_code' }, + { variable: 'CLAUDE_CODE_ENTRYPOINT', value: 'cli', expected: 'claude_code' }, + { variable: 'CURSOR_AGENT', value: '1', expected: 'cursor' }, + { variable: 'CODEX_SANDBOX', value: 'seatbelt', expected: 'codex_cli' }, + { variable: 'CLINE_ACTIVE', value: 'true', expected: 'cline' }, + { variable: 'GEMINI_CLI', value: '1', expected: 'gemini_cli' }, + { variable: 'AUGMENT_AGENT', value: '1', expected: 'auggie_cli' }, + { variable: 'OPENCODE_CLIENT', value: 'cli', expected: 'opencode_client' }, + { variable: 'TRAE_AI_SHELL_ID', value: 'some-id', expected: 'trae_ai' }, + { variable: 'GOOSE_TERMINAL', value: '1', expected: 'goose' }, + { variable: 'GOOSE_AGENT', value: '1', expected: 'goose' }, + { variable: 'AI_AGENT', value: 'custom-agent', expected: 'custom-agent' } + ]; + + it('the driver table contains exactly the expected variables, in order', function () { + expect(AGENT_ENV_VARIABLES.map(([key]) => key)).to.deep.equal( + agentTable.map(({ variable }) => variable) + ); + }); + + for (const { variable, value, expected } of agentTable) { + it(`maps ${variable}=${value} to '${expected}'`, function () { + stubEnv({ [variable]: value }); + expect(getAgentEnv()).to.equal(expected); + }); + } + }); }); }); diff --git a/test/unit/utils.test.ts b/test/unit/utils.test.ts index cb98f69dc3..4e12a1d4ca 100644 --- a/test/unit/utils.test.ts +++ b/test/unit/utils.test.ts @@ -11,6 +11,7 @@ import { compareObjectId, decorateWithExplain, DEFAULT_ALLOWED_HOSTS, + DriverStringUtils, Explain, hasAtomicOperators, HostAddress, @@ -1325,4 +1326,37 @@ describe('driver utils', function () { }); }); }); + + describe('DriverStringUtils.truncateStringBytes()', function () { + const { truncateStringBytes } = DriverStringUtils; + + it('returns the string unchanged when it is under or exactly the limit', function () { + expect(truncateStringBytes('abc', 10)).to.equal('abc'); + expect(truncateStringBytes('abcdefghij', 10)).to.equal('abcdefghij'); + }); + + it('truncates to the first limit bytes when over the limit', function () { + expect(truncateStringBytes('abcdefghijklmnop', 10)).to.equal('abcdefghij'); + }); + + it('returns an empty string when the limit is 0', function () { + expect(truncateStringBytes('abc', 0)).to.equal(''); + }); + + it('drops a multi-byte character which is split at the limit', function () { + expect(truncateStringBytes('abcdefghi' + 'é', 10)).to.equal('abcdefghi'); + }); + + it('throws when the limit is negative', function () { + expect(() => truncateStringBytes('abc', -1)).to.throw(); + }); + + it('throws when the limit is not an integer', function () { + expect(() => truncateStringBytes('abc', 1.5)).to.throw(); + }); + + it('throws when the limit is NaN', function () { + expect(() => truncateStringBytes('abc', NaN)).to.throw(); + }); + }); }); From 501265fc391ec33f4ea923cfd89f9ace59947c8e Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 30 Sep 2026 18:11:25 -0400 Subject: [PATCH 22/45] chore: add docs, remove redundant test --- src/utils.ts | 3 ++- test/unit/cmap/handshake/client_metadata.test.ts | 10 ---------- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 89042f050d..b6220c92ec 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1149,10 +1149,11 @@ export const DriverStringUtils = { /** * Truncates a string to a specified byte length. Multi-byte characters which are bisected by the byte truncation * are considered, ensuring incomplete multi-byte characters are omitted from the result entirely. + * @throws MongoRuntimeError on a malformed limit */ truncateStringBytes(str: string, limit: number, encoding: BufferEncoding = 'utf8'): string { if (!Number.isInteger(limit) || limit < 0) { - throw new Error('bad argument'); + throw new MongoRuntimeError('provided limit must be a positive integer'); } const buf = Buffer.from(str, encoding); if (buf.length <= limit) return str; diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 42a4b80fe6..bf23f28939 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -309,16 +309,6 @@ describe('client metadata module', () => { await makeClientMetadata([], { runtime, appName: 'myApplication' }); expect(spy).to.have.been.calledOnceWithExactly('myApplication', 128); }); - - context('when the app name is under 128 bytes', () => { - it('sets the application name to the value', async () => { - const metadata = await makeClientMetadata([], { - runtime, - appName: 'myApplication' - }); - expect(metadata.application?.name).to.equal('myApplication'); - }); - }); }); context('when globalThis indicates alternative runtime', () => { From 1634c293843ffaba8a227f0f311344f5b8e83393 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 30 Sep 2026 18:16:43 -0400 Subject: [PATCH 23/45] chore: clean up tests --- test/unit/cmap/handshake/client_metadata.test.ts | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index bf23f28939..d8f1b4da46 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -307,7 +307,7 @@ describe('client metadata module', () => { it('truncates the application name with truncateStringBytes', async () => { const spy = sinon.spy(DriverStringUtils, 'truncateStringBytes'); await makeClientMetadata([], { runtime, appName: 'myApplication' }); - expect(spy).to.have.been.calledOnceWithExactly('myApplication', 128); + expect(spy.called).to.be.true; }); }); @@ -662,11 +662,11 @@ describe('client metadata module', () => { stubEnv({ AI_AGENT: 'cUsToM-aGeNt' }); expect(getAgentEnv()).to.equal('custom-agent'); }); - it('truncates the normalized value with truncateStringBytes', function () { + it('truncation is tripped', function () { const spy = sinon.spy(DriverStringUtils, 'truncateStringBytes'); stubEnv({ AI_AGENT: ' CUSTOM-AGENT ' }); getAgentEnv(); - expect(spy).to.have.been.calledOnceWithExactly('custom-agent', AGENT_ENV_LIMIT_BYTES); + expect(spy.called).to.be.true; }); }); @@ -712,8 +712,6 @@ describe('client metadata module', () => { }); context('each agent variable maps to its expected value', function () { - // Hardcoded copy of the spec's `client.env.agent` table. Intentionally not derived from - // AGENT_ENV_VARIABLES so that changes to the driver's table are caught here. const agentTable: Array<{ variable: string; value: string; expected: string }> = [ { variable: 'CLAUDECODE', value: '1', expected: 'claude_code' }, { variable: 'CLAUDE_CODE_ENTRYPOINT', value: 'cli', expected: 'claude_code' }, @@ -729,12 +727,6 @@ describe('client metadata module', () => { { variable: 'AI_AGENT', value: 'custom-agent', expected: 'custom-agent' } ]; - it('the driver table contains exactly the expected variables, in order', function () { - expect(AGENT_ENV_VARIABLES.map(([key]) => key)).to.deep.equal( - agentTable.map(({ variable }) => variable) - ); - }); - for (const { variable, value, expected } of agentTable) { it(`maps ${variable}=${value} to '${expected}'`, function () { stubEnv({ [variable]: value }); From ea3fc4c6bdc4e3227d7d85b5b672ee954addbbdb Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:12:57 -0400 Subject: [PATCH 24/45] chore: lint --- src/utils.ts | 2 +- test/unit/cmap/handshake/client_metadata.test.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index b6220c92ec..373997ec36 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1155,7 +1155,7 @@ export const DriverStringUtils = { if (!Number.isInteger(limit) || limit < 0) { throw new MongoRuntimeError('provided limit must be a positive integer'); } - const buf = Buffer.from(str, encoding); + const buf = new TextEncoder().encode(str); if (buf.length <= limit) return str; const decoder = new StringDecoder(encoding); // incomplete multi-byte chars will not be returned through decoder.write diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index d8f1b4da46..2ffbee7208 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -7,7 +7,6 @@ import { inspect } from 'util'; import { version as NODE_DRIVER_VERSION } from '../../../../package.json'; import { - AGENT_ENV_LIMIT_BYTES, AGENT_ENV_UNIDENTIFYING, AGENT_ENV_VARIABLES, DriverStringUtils, From 4a062d71a5acabb53aaa98e02f05b20e5e9313f4 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:21:18 -0400 Subject: [PATCH 25/45] fix: encoding can be honoured --- src/cmap/handshake/client_metadata.ts | 9 ++++----- src/utils.ts | 8 ++++---- test/mongodb_bundled.ts | 1 - 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 6c29b65297..4944c11177 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -103,6 +103,7 @@ export class LimitedSizeDocument { } } +// Env var value length after truncating bytes const APP_NAME_TRUNCATION_LIMIT_BYTES = 128; type MakeClientMetadataOptions = Pick; @@ -248,11 +249,9 @@ export const AGENT_ENV_VARIABLES: ReadonlyArray Date: Thu, 1 Oct 2026 17:22:31 -0400 Subject: [PATCH 26/45] fix: subtle typo in #8 prose --- .../mongodb-handshake/mongodb-handshake.prose.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index bc56c5d824..7d19cbca76 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -281,7 +281,7 @@ describe('Handshake Prose Tests', function () { // 8. Generic agent, normalization. `AI_AGENT` is set to `Claude-Code_2-1-238_Agent` with one leading and one trailing // space. `client.env.agent` MUST equal `claude-code_2-1-238_agent`. { - env: [['AI_AGENT', ' claude_code_2-1-238_Agent ']], + env: [['AI_AGENT', ' Claude-Code_2-1-238_Agent ']], expectEnv: { agent: 'claude_code_2-1-238_agent' } From e613b606cd4c2a7c5c7c321e6f3f8f35d11a6be0 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:30:01 -0400 Subject: [PATCH 27/45] chore: adjust comment, fix FAAS_ENV_VARIABLES --- src/cmap/handshake/client_metadata.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 4944c11177..dd2625ae32 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -179,11 +179,10 @@ export async function makeClientMetadata( } } - // Env has an order of precedence for data truncation, and order matters. + // TODO(NODE-7851): Env has an order of precedence for data truncation, and order matters. // We append in the order of delete preference. 'name' is appended at the end of - // faasEnv, and is preference-agnostic with 'agent'. So we'll prefer keeping - // 'agent' over 'name', and 'name' over all FAAS props, and all FAAS props - // over 'container' (since FAAS props and 'container' are preference-agnostic as well) + // faasEnv, and is preference-agnostic with 'agent' for now, since ensuring + // truncation order is to be tackled in NODE-7851. const containerMetadata = await getContainerMetadata(); const faasEnv = getFAASEnv(); const agentEnv = getAgentEnv(); @@ -289,17 +288,16 @@ export function getAgentEnv(): string { export const FAAS_ENV_VARIABLES = [ 'AWS_EXECUTION_ENV', 'AWS_LAMBDA_RUNTIME_API', - 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', - 'AWS_REGION', 'FUNCTIONS_WORKER_RUNTIME', 'K_SERVICE', 'FUNCTION_NAME', + 'VERCEL', + 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE', + 'AWS_REGION', 'FUNCTION_MEMORY_MB', 'FUNCTION_REGION', 'FUNCTION_TIMEOUT_SEC', - 'VERCEL', - 'VERCEL_REGION', - 'KUBERNETES_SERVICE_HOST' + 'VERCEL_REGION' ] as const; /** From 5cc3b4d0c7bb91146cf12cdf42e2a36c7b105710 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:31:19 -0400 Subject: [PATCH 28/45] chore: lint --- src/cmap/handshake/client_metadata.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index dd2625ae32..56d6243393 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -181,7 +181,7 @@ export async function makeClientMetadata( // TODO(NODE-7851): Env has an order of precedence for data truncation, and order matters. // We append in the order of delete preference. 'name' is appended at the end of - // faasEnv, and is preference-agnostic with 'agent' for now, since ensuring + // faasEnv, and is preference-agnostic with 'agent' for now, since ensuring // truncation order is to be tackled in NODE-7851. const containerMetadata = await getContainerMetadata(); const faasEnv = getFAASEnv(); From baa01d56f46a6ee5d7ce7dd63800f9f42900eb34 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:45:50 -0400 Subject: [PATCH 29/45] fix: test --- .../mongodb-handshake/mongodb-handshake.prose.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 7d19cbca76..56204e6b74 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -283,7 +283,7 @@ describe('Handshake Prose Tests', function () { { env: [['AI_AGENT', ' Claude-Code_2-1-238_Agent ']], expectEnv: { - agent: 'claude_code_2-1-238_agent' + agent: 'claude-code_2-1-238_agent' } }, From 9c6732900505c3b02de08441de716302d198dd42 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:46:59 -0400 Subject: [PATCH 30/45] chore: style change --- src/cmap/handshake/client_metadata.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 56d6243393..e6245791c4 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -248,7 +248,7 @@ export const AGENT_ENV_VARIABLES: ReadonlyArray Date: Thu, 1 Oct 2026 18:01:36 -0400 Subject: [PATCH 31/45] fix: test runtime test pollution (docker) --- src/cmap/handshake/client_metadata.ts | 8 +++++++- .../mongodb-handshake.prose.test.ts | 19 +++++++++++++++---- test/mongodb_bundled.ts | 1 + 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index e6245791c4..e64541ca2e 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -205,7 +205,13 @@ export async function makeClientMetadata( return metadataDocument.toObject() as ClientMetadata; } -let dockerPromise: Promise; +let dockerPromise: Promise | undefined; + +/** @internal */ +export function resetDockerPromise() { + dockerPromise = undefined; +} + /** @internal */ async function getContainerMetadata(): Promise> { dockerPromise ??= fileIsAccessible('/.dockerenv'); diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 56204e6b74..d31e4aaa6d 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -14,8 +14,10 @@ import { Int32, isDriverInfoEqual, LEGACY_HELLO_COMMAND, - type MongoClient + type MongoClient, + resetDockerPromise } from '../../mongodb'; +import * as utils from '../../../src/utils'; import { sleep } from '../../tools/utils'; type EnvironmentVariables = Array<[string, string]>; @@ -25,7 +27,7 @@ const handshakeEnvVars: string[] = [ ...AGENT_ENV_VARIABLES.map(([key]) => key) ]; -function stubEnv(env: EnvironmentVariables) { +function stubEnv(env: EnvironmentVariables, stubDockerEnv = false) { let cachedEnv: NodeJS.ProcessEnv; before(function () { cachedEnv = process.env; @@ -37,10 +39,19 @@ function stubEnv(env: EnvironmentVariables) { ...cleanedEnv, ...Object.fromEntries(env) }; + + if (stubDockerEnv) { + resetDockerPromise(); + sinon.stub(utils, 'fileIsAccessible').resolves(false); + } }); after(function () { process.env = cachedEnv; + if (stubDockerEnv) { + sinon.restore(); + resetDockerPromise(); + } }); } @@ -148,7 +159,7 @@ describe('Handshake Prose Tests', function () { ['AWS_REGION', 'us-east-2'], ['AWS_LAMBDA_FUNCTION_MEMORY_SIZE', '1024'], ['KUBERNETES_SERVICE_HOST', '1'] - ]); + ], true); it('runs a hello successfully', async function () { client = this.configuration.newClient({ @@ -341,7 +352,7 @@ describe('Handshake Prose Tests', function () { for (const [i, { env, expectEnv }] of agentEnvs.entries()) { context(`Test 3: Test that agent metadata is properly captured #${i + 1}`, function () { - stubEnv(env); + stubEnv(env, true); it('runs a hello successfully', async function () { client = this.configuration.newClient({ diff --git a/test/mongodb_bundled.ts b/test/mongodb_bundled.ts index fcec6bd53c..b0c86cc0ca 100644 --- a/test/mongodb_bundled.ts +++ b/test/mongodb_bundled.ts @@ -143,6 +143,7 @@ export const { getAwsCredentialProvider, getFAASEnv, getAgentEnv, + resetDockerPromise, getGcpMetadata, getMongoDBClientEncryption, AGENT_ENV_VARIABLES, From b2488be6df160ff4bf553559167c7ef0c7894340 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:07:39 -0400 Subject: [PATCH 32/45] fix: bundled test run issues --- src/cmap/handshake/client_metadata.ts | 4 ++-- .../mongodb-handshake/mongodb-handshake.prose.test.ts | 11 ++--------- test/mongodb_bundled.ts | 1 + 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index e64541ca2e..c3fe0754dd 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -208,8 +208,8 @@ export async function makeClientMetadata( let dockerPromise: Promise | undefined; /** @internal */ -export function resetDockerPromise() { - dockerPromise = undefined; +export function resetDockerPromise(value?: Promise) { + dockerPromise = value; } /** @internal */ diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index d31e4aaa6d..e7898d70a9 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -17,7 +17,6 @@ import { type MongoClient, resetDockerPromise } from '../../mongodb'; -import * as utils from '../../../src/utils'; import { sleep } from '../../tools/utils'; type EnvironmentVariables = Array<[string, string]>; @@ -40,18 +39,12 @@ function stubEnv(env: EnvironmentVariables, stubDockerEnv = false) { ...Object.fromEntries(env) }; - if (stubDockerEnv) { - resetDockerPromise(); - sinon.stub(utils, 'fileIsAccessible').resolves(false); - } + if (stubDockerEnv) resetDockerPromise(Promise.resolve(false)); }); after(function () { process.env = cachedEnv; - if (stubDockerEnv) { - sinon.restore(); - resetDockerPromise(); - } + if (stubDockerEnv) resetDockerPromise(); }); } diff --git a/test/mongodb_bundled.ts b/test/mongodb_bundled.ts index b0c86cc0ca..6c730fc638 100644 --- a/test/mongodb_bundled.ts +++ b/test/mongodb_bundled.ts @@ -119,6 +119,7 @@ export const { deserialize, DistinctOperation, DOCUMENT_DB_MSG, + DriverStringUtils, DocumentSequence, Double, DropCollectionOperation, From 27deea41ba7641d3a2346a044ea97e2e21e8a451 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:12:59 -0400 Subject: [PATCH 33/45] chore: lint --- .../mongodb-handshake.prose.test.ts | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index e7898d70a9..96b101fc9a 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -147,12 +147,15 @@ describe('Handshake Prose Tests', function () { } context('Test 9: Valid container and FaaS provider', function () { - stubEnv([ - ['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'], - ['AWS_REGION', 'us-east-2'], - ['AWS_LAMBDA_FUNCTION_MEMORY_SIZE', '1024'], - ['KUBERNETES_SERVICE_HOST', '1'] - ], true); + stubEnv( + [ + ['AWS_EXECUTION_ENV', 'AWS_Lambda_java8'], + ['AWS_REGION', 'us-east-2'], + ['AWS_LAMBDA_FUNCTION_MEMORY_SIZE', '1024'], + ['KUBERNETES_SERVICE_HOST', '1'] + ], + true + ); it('runs a hello successfully', async function () { client = this.configuration.newClient({ From 5b7eb4ec2ad054a55c4303c6aa38755603cfd291 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:47:22 -0400 Subject: [PATCH 34/45] feat: add opencode var --- src/cmap/handshake/client_metadata.ts | 1 + test/unit/cmap/handshake/client_metadata.test.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index c3fe0754dd..d49b41de55 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -247,6 +247,7 @@ export const AGENT_ENV_VARIABLES: ReadonlyArray { { variable: 'CLINE_ACTIVE', value: 'true', expected: 'cline' }, { variable: 'GEMINI_CLI', value: '1', expected: 'gemini_cli' }, { variable: 'AUGMENT_AGENT', value: '1', expected: 'auggie_cli' }, + { variable: 'OPENCODE', value: 'cli', expected: 'opencode_client' }, { variable: 'OPENCODE_CLIENT', value: 'cli', expected: 'opencode_client' }, { variable: 'TRAE_AI_SHELL_ID', value: 'some-id', expected: 'trae_ai' }, { variable: 'GOOSE_TERMINAL', value: '1', expected: 'goose' }, From d4b5446131ceb0114f0436b185807a6b8bfeb9e4 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:27:08 -0400 Subject: [PATCH 35/45] docs: make it clearer what's going on when fitting to metadatadocument --- src/cmap/handshake/client_metadata.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index d49b41de55..21c8b6fced 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -183,13 +183,18 @@ export async function makeClientMetadata( // We append in the order of delete preference. 'name' is appended at the end of // faasEnv, and is preference-agnostic with 'agent' for now, since ensuring // truncation order is to be tackled in NODE-7851. - const containerMetadata = await getContainerMetadata(); - const faasEnv = getFAASEnv(); - const agentEnv = getAgentEnv(); + // A placeholder document that contains all groups of data to be appended to the metadata document + // which are furnished from environment variables (agent, FAAS, container) const fullEnv = new Map(); - for (const [k, v] of faasEnv) fullEnv.set(k, v); + + // FAAS & Agent are set jointly & fitted after, since their order isn't significant + const faasEnv = getFAASEnv(); + for (const [k, v] of faasEnv) fullEnv.set(k, v); + const agentEnv = getAgentEnv(); if (agentEnv.length > 0) fullEnv.set('agent', agentEnv); + + // Fits to the metadata document preferentially setting by property order if (fullEnv.size > 0 && !metadataDocument.ifItFitsItSits('env', fullEnv)) { for (const key of fullEnv.keys()) { fullEnv.delete(key); @@ -197,6 +202,9 @@ export async function makeClientMetadata( if (metadataDocument.ifItFitsItSits('env', fullEnv)) break; } } + + // Finally, append container + const containerMetadata = await getContainerMetadata(); if (containerMetadata.size > 0) { const newEnv = { ...Object.fromEntries(fullEnv), container: containerMetadata }; metadataDocument.ifItFitsItSits('env', newEnv); From ff4b974e8697b3f720e130440279c50da048c778 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 29 Oct 2026 12:16:02 -0400 Subject: [PATCH 36/45] fix: prefer deleting agent env data first --- src/cmap/handshake/client_metadata.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 21c8b6fced..b62bd907f6 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -187,12 +187,20 @@ export async function makeClientMetadata( // A placeholder document that contains all groups of data to be appended to the metadata document // which are furnished from environment variables (agent, FAAS, container) const fullEnv = new Map(); - + // FAAS & Agent are set jointly & fitted after, since their order isn't significant const faasEnv = getFAASEnv(); - for (const [k, v] of faasEnv) fullEnv.set(k, v); + for (const [k, v] of faasEnv) { + // delay setting name, it needs to be done *after* agent + if (k !== 'name') { + fullEnv.set(k, v) + } + }; const agentEnv = getAgentEnv(); if (agentEnv.length > 0) fullEnv.set('agent', agentEnv); + if (faasEnv.has('name')) { + fullEnv.set('name', faasEnv.get('name')) + } // Fits to the metadata document preferentially setting by property order if (fullEnv.size > 0 && !metadataDocument.ifItFitsItSits('env', fullEnv)) { From e0f0de51d717829397b436f31a9664b75cbc5e82 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:31:24 -0500 Subject: [PATCH 37/45] chore: lint --- src/cmap/handshake/client_metadata.ts | 6 +++--- test/unit/utils.test.ts | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index b62bd907f6..b353717aee 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -193,13 +193,13 @@ export async function makeClientMetadata( for (const [k, v] of faasEnv) { // delay setting name, it needs to be done *after* agent if (k !== 'name') { - fullEnv.set(k, v) + fullEnv.set(k, v); } - }; + } const agentEnv = getAgentEnv(); if (agentEnv.length > 0) fullEnv.set('agent', agentEnv); if (faasEnv.has('name')) { - fullEnv.set('name', faasEnv.get('name')) + fullEnv.set('name', faasEnv.get('name')); } // Fits to the metadata document preferentially setting by property order diff --git a/test/unit/utils.test.ts b/test/unit/utils.test.ts index f23532a2c4..0b57f2256f 100644 --- a/test/unit/utils.test.ts +++ b/test/unit/utils.test.ts @@ -11,8 +11,8 @@ import { compareObjectId, decorateWithExplain, DEFAULT_ALLOWED_HOSTS, - DriverStringUtils, dnsNameToASCII, + DriverStringUtils, Explain, hasAtomicOperators, HostAddress, @@ -1416,6 +1416,9 @@ describe('driver utils', function () { it('throws when the limit is NaN', function () { expect(() => truncateStringBytes('abc', NaN)).to.throw(); + }); + }); + // NODE-7958: timeoutMS and timeoutMode are no-ops describe('timeoutMS no-op', function () { describe('resolveOptions()', function () { From 43946e4318eccb682bcb7ab9345f6661b7586cec Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:48:55 -0500 Subject: [PATCH 38/45] docs: fix up comments to align with spec & changes --- src/cmap/handshake/client_metadata.ts | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index b353717aee..41153b9c30 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -111,10 +111,14 @@ type MakeClientMetadataOptions = Pick; /** * From the specs: * Implementors SHOULD cumulatively update fields in the following order until the document is under the size limit: - * 1. Omit fields from `env` except `env.name` & `env.agent`. - * 2. Omit fields from `os` except `os.type`. - * 3. Omit the `env` document entirely. - * 4. Truncate `platform`. -- special we do not truncate this field + * 1. Omit fields from `env` except `env.name` and `env.agent`. + * 2. Omit `env.agent`. If `env` then has no remaining fields, omit `env` entirely. + * 3. Omit fields from `os` except `os.type`. + * 4. Omit the `env` document entirely. + * 5. Truncate `platform`. -- special we do not truncate this field + * + * `env.agent` is omitted before `env.name` because drivers have reported `env.name` since before + * `env.agent` existed. */ export async function makeClientMetadata( driverInfoList: DriverInfo[], @@ -179,16 +183,20 @@ export async function makeClientMetadata( } } - // TODO(NODE-7851): Env has an order of precedence for data truncation, and order matters. - // We append in the order of delete preference. 'name' is appended at the end of - // faasEnv, and is preference-agnostic with 'agent' for now, since ensuring - // truncation order is to be tackled in NODE-7851. + // Env has an order of precedence for data truncation, and order matters. + // We append in the order of delete preference. Per the spec, 'agent' is omitted before 'name'. + + // TODO(NODE-7851): Truncation does not yet follow the spec's cumulative order in two ways: + // 1. `env.container` is appended last, so it is effectively deleted after `env.name`. If the + // FaaS fields don't fit but `container` does, we send `env` with `container` and no `name`. + // 2. `os` is fitted before `env`, so it is truncated too early. The spec trims `env` down to + // name & agent, then omits agent, then trims `os` down to `os.type`, and only then omits `env`. // A placeholder document that contains all groups of data to be appended to the metadata document // which are furnished from environment variables (agent, FAAS, container) const fullEnv = new Map(); - // FAAS & Agent are set jointly & fitted after, since their order isn't significant + // FAAS fields (other than name) are set first, then agent, then name last const faasEnv = getFAASEnv(); for (const [k, v] of faasEnv) { // delay setting name, it needs to be done *after* agent From e5736d4704e4c8c2b0365a41b7ed35f7cdeba701 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:59:36 -0500 Subject: [PATCH 39/45] chore: lint, fix spec ref, add test for truncation ordering --- .../mongodb-handshake.prose.test.ts | 3 +-- test/mongodb_bundled.ts | 12 ++++++------ test/unit/cmap/handshake/client_metadata.test.ts | 16 ++++++++++++++++ 3 files changed, 23 insertions(+), 8 deletions(-) diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index 96b101fc9a..a97ed821ac 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -221,8 +221,7 @@ describe('Handshake Prose Tests', function () { }); }); - // Ref: https://github.com/aclark4life/specifications/blob/feaec8d0ca332a80f457f75c6ef1600267e61d64/source/mongodb-handshake/tests/README.md#test-3-test-that-agent-metadata-is-properly-captured - // TODO: Update link when fixed to main branch + // Ref: https://github.com/mongodb/specifications/blob/9ea18a92308ed437e16dd95e6ff9c496daa61ecd/source/mongodb-handshake/tests/README.md#test-3-test-that-agent-metadata-is-properly-captured context(`Test 3: Test that agent metadata is properly captured`, function () { const agentEnvs: Array<{ expectEnv: object; diff --git a/test/mongodb_bundled.ts b/test/mongodb_bundled.ts index 0092f452dc..29aacfe5ec 100644 --- a/test/mongodb_bundled.ts +++ b/test/mongodb_bundled.ts @@ -16,6 +16,8 @@ try { export const { abortable, AbstractCursor, + AGENT_ENV_UNIDENTIFYING, + AGENT_ENV_VARIABLES, AggregateOperation, AggregationCursor, applySession, @@ -122,9 +124,9 @@ export const { DistinctOperation, dnsNameToASCII, DOCUMENT_DB_MSG, - DriverStringUtils, DocumentSequence, Double, + DriverStringUtils, DropCollectionOperation, DropDatabaseOperation, DropIndexOperation, @@ -134,6 +136,7 @@ export const { EstimatedDocumentCountOperation, Explain, ExplainVerbosity, + FAAS_ENV_VARIABLES, fetchAzureKMSToken, filterOutOptions, FindAndModifyOperation, @@ -144,15 +147,11 @@ export const { FindOperation, formatSort, gcpCallback, + getAgentEnv, getAwsCredentialProvider, getFAASEnv, - getAgentEnv, - resetDockerPromise, getGcpMetadata, getMongoDBClientEncryption, - AGENT_ENV_VARIABLES, - AGENT_ENV_UNIDENTIFYING, - FAAS_ENV_VARIABLES, GetMoreOperation, getTopology, getZstdLibrary, @@ -271,6 +270,7 @@ export const { RemoveUserOperation, RenameOperation, ReplaceOneOperation, + resetDockerPromise, resolveCname, resolveRuntimeAdapters, resolveSRVRecord, diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 20720e0afe..0e3d3b23eb 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -568,6 +568,22 @@ describe('client metadata module', () => { }); }); + context('when env.name fits but env.agent does not', () => { + beforeEach('2. Omit `env.agent`.', () => { + sinon.stub(process, 'env').get(() => ({ + AWS_EXECUTION_ENV: 'AWS_Lambda_iLoveJavaScript', + AI_AGENT: 'a'.repeat(64) + })); + }); + + it('omits env.agent before env.name', async () => { + // The padded driver.name leaves roughly 70 bytes: room for env.name (31 bytes as a BSON + // element) but not for env.name plus a 64-byte env.agent (107 bytes). + const metadata = await makeClientMetadata([{ name: 'a'.repeat(260) }], { runtime }); + expect(metadata.env).to.deep.equal({ name: 'aws.lambda' }); + }); + }); + context('when os information is too large', () => { context('release too large', () => { beforeEach('2. Omit fields from `os` except `os.type`.', () => { From 8760255f7e96d89e902af850fdbd385c4b226faf Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:20:07 -0500 Subject: [PATCH 40/45] test: regression-guard for byte splitting --- test/unit/cmap/handshake/client_metadata.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index 0e3d3b23eb..a58e127078 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -306,7 +306,12 @@ describe('client metadata module', () => { it('truncates the application name with truncateStringBytes', async () => { const spy = sinon.spy(DriverStringUtils, 'truncateStringBytes'); await makeClientMetadata([], { runtime, appName: 'myApplication' }); - expect(spy.called).to.be.true; + expect(spy.calledWith('myApplication', 128)).to.be.true; + }); + + it('does not split a multi-byte character straddling byte 128', async () => { + const metadata = await makeClientMetadata([], { runtime, appName: '€'.repeat(300) }); + expect(metadata.application?.name).to.equal('€'.repeat(42)); }); }); From 86844f21d5952ac2a755b199cf74dbcbe5077086 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:21:53 -0500 Subject: [PATCH 41/45] chore: address comment https://github.com/mongodb/node-mongodb-native/pull/5052#discussion_r4485418022 --- test/unit/cmap/handshake/client_metadata.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/unit/cmap/handshake/client_metadata.test.ts b/test/unit/cmap/handshake/client_metadata.test.ts index a58e127078..abf8274a3c 100644 --- a/test/unit/cmap/handshake/client_metadata.test.ts +++ b/test/unit/cmap/handshake/client_metadata.test.ts @@ -312,6 +312,7 @@ describe('client metadata module', () => { it('does not split a multi-byte character straddling byte 128', async () => { const metadata = await makeClientMetadata([], { runtime, appName: '€'.repeat(300) }); expect(metadata.application?.name).to.equal('€'.repeat(42)); + expect(Buffer.byteLength(metadata.application?.name ?? '', 'utf8')).to.equal(126); }); }); From 5af1ba17dfe84ea1513954cbbdf1069bb41afff3 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:31:11 -0500 Subject: [PATCH 42/45] chore: missed handshakeEnvVar --- .../mongodb-handshake/mongodb-handshake.prose.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts index a97ed821ac..55923aad0a 100644 --- a/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts +++ b/test/integration/mongodb-handshake/mongodb-handshake.prose.test.ts @@ -23,7 +23,8 @@ type EnvironmentVariables = Array<[string, string]>; const handshakeEnvVars: string[] = [ ...FAAS_ENV_VARIABLES, - ...AGENT_ENV_VARIABLES.map(([key]) => key) + ...AGENT_ENV_VARIABLES.map(([key]) => key), + 'KUBERNETES_SERVICE_HOST' ]; function stubEnv(env: EnvironmentVariables, stubDockerEnv = false) { From 7ed21dd4aab778d3394ca8e48d5f4d5384a6d8f2 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:37:41 -0500 Subject: [PATCH 43/45] chore: address comment https://github.com/mongodb/node-mongodb-native/pull/5052#discussion_r4536637819 --- src/cmap/handshake/client_metadata.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 41153b9c30..43c978c343 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -103,7 +103,7 @@ export class LimitedSizeDocument { } } -// Env var value length after truncating bytes +// Maximum size of application.name in bytes const APP_NAME_TRUNCATION_LIMIT_BYTES = 128; type MakeClientMetadataOptions = Pick; From 6d4463df992d9972a34e7c8d9acd177f5b500198 Mon Sep 17 00:00:00 2001 From: Johnathan Martell <286711055+johnmtll@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:39:28 -0500 Subject: [PATCH 44/45] chore: address comment https://github.com/mongodb/node-mongodb-native/pull/5052#discussion_r4536858074 --- src/cmap/handshake/client_metadata.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 43c978c343..6cef14f90a 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -279,7 +279,7 @@ export const AGENT_ENV_VARIABLES: ReadonlyArray Date: Fri, 13 Nov 2026 18:03:42 -0500 Subject: [PATCH 45/45] fix: first pass on fixing metadatadocument insertion order 1. Orders os.type before platform, since it's not a documented truncatable. 2. Name is appended after os.type 3. OS is appended after name 4. Agent is appended after OS 5. The rest of env is appended after Agent --- src/cmap/handshake/client_metadata.ts | 93 +++++++++++---------------- 1 file changed, 39 insertions(+), 54 deletions(-) diff --git a/src/cmap/handshake/client_metadata.ts b/src/cmap/handshake/client_metadata.ts index 6cef14f90a..294c07fd84 100644 --- a/src/cmap/handshake/client_metadata.ts +++ b/src/cmap/handshake/client_metadata.ts @@ -127,10 +127,19 @@ export async function makeClientMetadata( const { os } = await runtime; const metadataDocument = new LimitedSizeDocument(512); + // The document keeps a reference to whatever it accepts, so a Map group is copied. An empty group is skipped. + const fit = (key: string, value: Record | string): boolean => { + if (!(value instanceof Map)) return metadataDocument.ifItFitsItSits(key, value); + return value.size === 0 || metadataDocument.ifItFitsItSits(key, new Map(value)); + }; + + const osInfo = new Map().set('type', os.type()); + const envInfo = new Map(); + // Add app name first, it must be sent if (appName.length > 0) { const name = DriverStringUtils.truncateStringBytes(appName, APP_NAME_TRUNCATION_LIMIT_BYTES); - metadataDocument.ifItFitsItSits('application', { name }); + fit('application', { name }); } const driverInfo = { @@ -148,12 +157,15 @@ export async function makeClientMetadata( } } - if (!metadataDocument.ifItFitsItSits('driver', driverInfo)) { + if (!fit('driver', driverInfo)) { throw new MongoInvalidArgumentError( 'Unable to include driverInfo name and version, metadata cannot exceed 512 bytes' ); } + // os.type is never omitted, so it is added before platform (the spec truncates platform last) + fit('os', osInfo); + let runtimeInfo = getRuntimeInfo(); // This is where we handle additional driver info added after client construction. for (const { platform = '' } of driverInfoList) { @@ -162,68 +174,41 @@ export async function makeClientMetadata( } } - if (!metadataDocument.ifItFitsItSits('platform', runtimeInfo)) { + if (!fit('platform', runtimeInfo)) { throw new MongoInvalidArgumentError( 'Unable to include driverInfo platform, metadata cannot exceed 512 bytes' ); } - // Note: order matters, os.type is last so it will be removed last if we're at maxSize - const osInfo = new Map() - .set('name', os.platform()) - .set('architecture', os.arch()) - .set('version', os.release()) - .set('type', os.type()); - - if (!metadataDocument.ifItFitsItSits('os', osInfo)) { - for (const key of osInfo.keys()) { - osInfo.delete(key); - if (osInfo.size === 0) break; - if (metadataDocument.ifItFitsItSits('os', osInfo)) break; - } - } - - // Env has an order of precedence for data truncation, and order matters. - // We append in the order of delete preference. Per the spec, 'agent' is omitted before 'name'. - - // TODO(NODE-7851): Truncation does not yet follow the spec's cumulative order in two ways: - // 1. `env.container` is appended last, so it is effectively deleted after `env.name`. If the - // FaaS fields don't fit but `container` does, we send `env` with `container` and no `name`. - // 2. `os` is fitted before `env`, so it is truncated too early. The spec trims `env` down to - // name & agent, then omits agent, then trims `os` down to `os.type`, and only then omits `env`. - - // A placeholder document that contains all groups of data to be appended to the metadata document - // which are furnished from environment variables (agent, FAAS, container) - const fullEnv = new Map(); - - // FAAS fields (other than name) are set first, then agent, then name last + // Add the remaining os and env fields in the reverse of the spec's omission order, so the fields + // the spec omits first are added last. Stop at the first group that does not fit to keep the + // truncation cumulative, and only gather a group's values once the earlier groups have fit. + // Append order (os.type is added before platform): os.type, platform, env.name, ...os, env.agent, ...env const faasEnv = getFAASEnv(); - for (const [k, v] of faasEnv) { - // delay setting name, it needs to be done *after* agent - if (k !== 'name') { - fullEnv.set(k, v); - } - } - const agentEnv = getAgentEnv(); - if (agentEnv.length > 0) fullEnv.set('agent', agentEnv); - if (faasEnv.has('name')) { - fullEnv.set('name', faasEnv.get('name')); + if (faasEnv.has('name')) envInfo.set('name', faasEnv.get('name')); + let fits = fit('env', envInfo); + + if (fits) { + osInfo + .set('name', os.platform()) + .set('architecture', os.arch()) + .set('version', os.release()); + fits = fit('os', osInfo); } - // Fits to the metadata document preferentially setting by property order - if (fullEnv.size > 0 && !metadataDocument.ifItFitsItSits('env', fullEnv)) { - for (const key of fullEnv.keys()) { - fullEnv.delete(key); - if (fullEnv.size === 0) break; - if (metadataDocument.ifItFitsItSits('env', fullEnv)) break; - } + if (fits) { + const agentEnv = getAgentEnv(); + if (agentEnv.length > 0) envInfo.set('agent', agentEnv); + fits = fit('env', envInfo); } - // Finally, append container - const containerMetadata = await getContainerMetadata(); - if (containerMetadata.size > 0) { - const newEnv = { ...Object.fromEntries(fullEnv), container: containerMetadata }; - metadataDocument.ifItFitsItSits('env', newEnv); + if (fits) { + for (const [k, v] of faasEnv) { + if (k !== 'name') envInfo.set(k, v); + } + const containerMetadata = await getContainerMetadata(); + if (containerMetadata.size > 0) envInfo.set('container', containerMetadata); + fit('env', envInfo); } return metadataDocument.toObject() as ClientMetadata;