DEV Community

Cover image for Tool Names Are Identifiers. Don't Autocorrect Them.

Tool Names Are Identifiers. Don't Autocorrect Them.

Homoglyph attacks break automated agent contracts

An agent contract requires retrieve_policy. The trace seems to contain retrieve_policy. The evaluator says the tool is missing.

Before changing the contract, inspect the characters.

const expected = "retrieve_policy";
const observed = "retrieve_p\u043Elicy";

console.log(expected === observed); // false
Enter fullscreen mode Exit fullscreen mode

The observed value contains a Cyrillic small letter o, U+043E, where the expected identifier contains Latin o, U+006F. In many fonts, the names look alike. They are different strings.

I maintain AgentInspect. This example was tested against 6.31.35, whose diagnostics can expose code points for certain suspicious names. The important design choice is not a clever Unicode trick: improve the explanation without silently changing the identifier being evaluated.

Equality and readability solve different problems

A tool name participates in a contract between a tool registry, an invocation, a trace adapter, and an evaluator. If those components disagree, forgiving display logic can hide a real integration defect.

Operation Appropriate purpose Risk if used for policy matching
Exact comparison Compare recorded identifiers May need better diagnostics for humans
Escaped/code-point display Explain visually ambiguous values Must not replace the raw identity
Friendly display label Make a UI readable Several identifiers may share a label
Case folding or normalization Explicitly designed naming schemes Can silently merge names under a different scheme

An allowlist is not a spellchecker. If the application authorizes one identifier, an adapter should not authorize a lookalike on its behalf.

This does not mean non-Latin tool names are invalid. The contract can explicitly allow a name in any supported naming scheme. The problem is disagreement between identities, not the language used to write them.

Two visually similar tool names have different code points, leading to exact mismatch and an explanatory diagnostic rather than automatic replacement.

Preserve identity; make the mismatch legible.

Reproduce the mismatch without an LLM

Install the pinned package and capture a synthetic invocation:

npm install --save-exact agent-inspect@6.31.35
Enter fullscreen mode Exit fullscreen mode
import { inspectRun, step } from "agent-inspect";

await inspectRun("unicode-name-fixture", async () => {
  return step.tool("retrieve_p\u043Elicy", async () => ({
    found: true,
  }));
}, { traceDir: ".agent-inspect", silent: true });
Enter fullscreen mode Exit fullscreen mode

The callback succeeds. That does not make the name match the contract. After opening the resulting trace with openTraceFile, evaluate:

import {
  defineTraceContract,
  evaluateTraceContractRead,
} from "agent-inspect/checks";

const contract = defineTraceContract({
  tools: {
    required: ["retrieve_policy"],
    allowed: ["retrieve_policy"],
  },
});

const result = evaluateTraceContractRead(trace, contract);
console.log(result.status, result.findings);
Enter fullscreen mode Exit fullscreen mode

The measured fixture fails. Its findings include the U+043E diagnostic. A positive control using the exact ASCII name passes.

The two constraints are complementary. required asks whether the expected tool occurred. allowed asks whether an unexpected tool occurred. Depending on your application, the meaningful report may include both a missing expected operation and an unrecognized observed one.

TraceContract remains a beta API. Keep the regression fixture pinned to the version used by your release gate.

Trace the mismatch back to its boundary

When a name differs, investigate the registry, serialized invocation, adapter mapping, and contract definition. A copied description may have become an identifier. A display label may have replaced a registered name. A normalization layer may have rewritten characters.

Do not assume an attack from this fixture alone. Copy/paste errors, inconsistent naming conventions, and adapter defects can produce the same symptom. Diagnostics should report the observed mismatch without making an unsupported claim about intent.

The same discipline applies to leading spaces, case changes, hidden controls, and aliases. First establish the application's naming contract. Then determine which boundary violated it.

If aliases are intentional, declare them in a reviewed mapping and version it. An undocumented “close enough” conversion makes later evidence harder to interpret.

Reduce opportunities for drift

For names you control, share constants between registration, invocation, and test expectations:

export const Tool = {
  retrievePolicy: "retrieve_policy",
  summarizePolicy: "summarize_policy",
} as const;

type ToolName = typeof Tool[keyof typeof Tool];

function acceptsRegisteredName(name: ToolName) {
  return name;
}
Enter fullscreen mode Exit fullscreen mode

The type prevents certain accidental literals in your own TypeScript code. It does not validate an untrusted runtime string. Validate external values at the boundary using the registry's actual identifiers.

Also separate identifiers from descriptions. A readable label can change during localization without renaming an operation. Conversely, changing the operation's identifier should trigger a deliberate migration of contracts and historical comparisons.

Keep diagnostic output bounded

A helpful error report shows the expected name, the observed name, and enough escaped or code-point information to explain the difference. It should not dump unbounded input into a terminal or report.

The current implementation applies additional code-point detail to selected mixed-script or risky-control cases; it is not a universal spoofing detector. A name that receives no extra diagnostic is not thereby trustworthy. Likewise, a name receiving a diagnostic is not automatically malicious.

Keep the raw captured evidence, the comparison result, and the human-friendly explanation conceptually separate. Each has a different job.

Don’t repair the evidence to make the test green

The tempting fix is to normalize the observed name into the expected one. That may make a fixture pass while hiding the actual mismatch.

A better fix corrects the naming boundary or explicitly updates the contract. Then rerun both the exact-match positive control and the lookalike negative control.

When an agent tool crosses registries, SDKs, adapters, and evaluators, a tiny identifier change can become a large debugging detour. The solution is exact policy and understandable diagnostics—not a more forgiving guess.

Implementation references

Top comments (25)

Collapse
 
dafili profile image
Renhua Wei •

The place this actually leaks is the validator, not the comparison. Python's \w is Unicode-aware by default, so re.match(r'^\w+$', name) matches the Cyrillic version and str.isidentifier() returns True for retrieve_pоlicy — I ran both against it just now and both said fine. Pin the boundary to ASCII instead, name.isascii() first or re.fullmatch with re.ASCII, otherwise the allow-list that is supposed to enforce the capability boundary accepts the homoglyph.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

Useful cross-language test, @dafili. \w and isidentifier() answer whether a string is a valid identifier under their rules, not whether it names a registered capability. ASCII is a good boundary if the registry contract is ASCII-only; for systems that intentionally support non-Latin names, I would still compare against the exact registered allowlist and report mixed-script surprises separately.

Collapse
 
dafili profile image
Renhua Wei •

Agreed, allowlist membership is the real gate and isascii only prunes the homoglyph class before it. The mixed-script report is the part I would make loud: name.isascii() or name.encode('ascii','strict') fails, log the codepoints (name.encode('unicode_escape')) not just the repr, because a Cyrillic о in retrieve_policy prints identically in a terminal and a screenshot of the log will lie to the next person debugging.

Thread Thread
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@dafili Agreed. A plain repr can be as misleading as the original glyph in some fonts. When exact allowlist membership fails, the diagnostic should show bounded escaped code points for expected and observed names. Keep isascii as a policy rule only where the registry actually promises ASCII.

Thread Thread
 
dafili profile image
Renhua Wei •

Bound by sequence count rather than characters: name.encode('unicode_escape') on a 300-char name turns one log line into a few KB, so cap the first 8 escapes plus a total byte length or the diagnostic becomes the outage. One step to add before comparison is unicodedata.normalize('NFC', name) on both sides, because a decomposed form is codepoint-different and renders identical, which is the same lie in a different encoding.

Collapse
 
mryo0826 profile image
mryo0826 •

We keep a written rule from a cousin of this scar: when a match comes back 'not found', suspect the string before the logic — records I copy identifiers from have smuggled in full-width punctuation more than once. Inspecting code points instead of eyeballing glyphs is the honest move. 'Equality and readability solve different problems' is going in my notes.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

Thanks, @mryo0826. Full-width punctuation is a great example of why a “not found” report should expose the exact characters, not just reprint a visually similar label. I would keep the raw identifier for matching and add a bounded escaped/code-point view for diagnosis, then fix the source that copied it into the contract.

Collapse
 
mryo0826 profile image
mryo0826 •

Thanks. The companion rule on my side, from the same scar: never retype an identifier out of a record — copy the exact string from its source, or don't use it. The full-width punctuation got in precisely because I read a value and typed it back from memory. Eyeballs are a lossy codec; the clipboard isn't.

Thread Thread
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@mryo0826 “Eyeballs are a lossy codec” is a useful rule. Copying from the registry avoids the first transcription error; I would still put an exact-match assertion at the boundary, since copied strings can drift through serialization or adapter mapping. The escaped diagnostic can then show where the mismatch entered.

Collapse
 
gautamtalksdev profile image
Gautam K •

"Seems to contain" is the dangerous part. Fuzzy matching tool names means an agent can claim it called the policy check when it called something with a similar name. Exact identifiers are the only safe comparison.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

Agreed, @gautamtalksdev. “Looks like the same tool” is useful only as a diagnostic hint for a human. The evaluator should keep the recorded identifier and fail the exact contract, then show the differing code points so the registry or adapter can be fixed at the right boundary.

Collapse
 
gautamtalksdev profile image
Gautam K •

Showing the differing code points is a great touch. Two names that look identical are impossible to tell apart by eye, but a list of code points makes the fix obvious in seconds.

Thread Thread
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@gautamtalksdev That is the value of the negative fixture: two visually identical names must still fail, and the finding should identify U+006F versus U+043E. Reviewers get a fast explanation without loosening the contract.

Collapse
 
maxbuildsdev profile image
Max Kaya •

Worth adding the trap that catches people trying to fix this with normalization: "retrieve_p\u043Elicy".normalize("NFKC").length stays the same and still !== the Latin version, because U+043E is a distinct Cyrillic letter, not a compatibility character. NFKC won't fold it, and neither will toLowerCase. So a "just normalize both sides" patch passes code review and changes nothing.

The check that does work is a confusable skeleton: map every name through UTS #39 skeleton() and compare that, while keeping the raw string for the actual dispatch. Cheap version without a library: flag any identifier that mixes scripts, e.g. /\p{Script=Latin}/u.test(n) && /\p{Script=Cyrillic}/u.test(n), and reject that at registry time with the offending code points printed. A mixed-script identifier is almost never intentional.

One question: does AgentInspect compare the trace's tool name against the registry after JSON-decoding, or before? A \u043E escape inside the recorded JSON is harmless once decoded, so flagging pre-decode would produce false positives on serialized traces.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

Good distinction, @maxbuildsdev. In this fixture openTraceFile has already parsed the JSON before evaluateTraceContractRead compares the tool-name strings, so an escaped spelling in the file is not itself the mismatch. The observed decoded character is. A confusable check can help at registration or in diagnostics, while exact matching remains the contract for dispatch and evaluation.

Collapse
 
paullovelace profile image
Paul Lovelace •

The "don't repair the evidence to make the test green" line is the one that landed for me — normalizing the lookalike name away is the same instinct as an agent deleting a failing assertion to get pytest green, and it hides the exact thing you need to see. Have you seen this bite in the wild outside the fixture, like a Cyrillic homoglyph slipping into a real trace from a copy-pasted tool description?

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

That analogy is apt, @paullovelace. I have not seen a confirmed Cyrillic homoglyph incident in a production trace; this is a controlled fixture meant to catch the boundary before one occurs. Copy/paste drift and adapter mappings are plausible sources, but I would want the raw registry name, recorded invocation, and contract side by side before assigning a cause.

Collapse
 
kursatyz profile image
Kürşat Yılmaz •

Fuzzy-matching tool identifiers in an agent runtime trades a loud schema failure for silent misrouting, masking contract drift in evals while turning strict capability boundaries into probabilistic guesses. Never autocorrect a capability boundary.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

That is the risk, @kursatyz. A loud contract failure gives the team a chance to inspect the registry, adapter, and recorded call. If two names truly are aliases, I would make that a reviewed, versioned mapping and test both spellings explicitly; a fuzzy fallback at evaluation time would hide the drift you need to diagnose.

Collapse
 
argumentmoney8117 profile image
ArgumentMoney8117 •

The registry-time rejection idea and the point about allowing names in any script seem to pull in opposite directions. A mixed-script name could be a deliberate identifier in a multilingual registry, not just a homoglyph. How do you draw that line in practice — is an explicit allowlist entry the only way to keep both, or is there a property of the name itself that makes rejection safe?

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@argumentmoney8117 You are right to separate registry policy from diagnostics. A mixed-script name can be valid if the registry intentionally declares it; exact membership in that registry is the authorization check. A registry may reject mixed scripts as its own naming rule, but the evaluator should not invent a universal ban or silently normalize.

Collapse
 
rosana_e4663528aeaba0b05b profile image
Rosana •

This is an important distinction that deserves far more attention in AI agent development: an identifier that looks correct to a human is not necessarily the same identifier to a computer. Your example with the Latin and Cyrillic “o” illustrates how a seemingly insignificant character difference can break an entire tool contract—and, more importantly, how a system can accidentally conceal that failure if it tries too hard to be helpful.

I particularly appreciate your argument that an allowlist is not a spellchecker. In an agent architecture, tool names aren't merely labels displayed in a user interface; they're part of the security and execution boundary between registries, adapters, invocation traces, and evaluators. If an evaluator silently normalizes a suspicious identifier into an authorized one, it risks turning a strict authorization check into a guess about what the caller intended. That is a dangerous trade-off, especially when agents can invoke tools with access to sensitive data or consequential operations.

The distinction between preserving raw evidence and improving its presentation is also excellent. Developers should be able to see an escaped representation or Unicode code points that explain why two visually identical strings fail comparison, without changing the underlying value. This is a broader principle in security engineering: diagnostics should make evidence easier to understand, not modify the evidence to make the system appear correct. The same applies to audit logs, authentication identifiers, filenames, and other values that cross trust boundaries.

I'd also extend this idea beyond homoglyphs. Unicode normalization, case folding, invisible characters, whitespace, and alternate representations can all create inconsistencies when different components apply different rules. The challenge isn't that Unicode is inherently unsafe or that non-Latin identifiers should be rejected. It's that every component needs to agree on the naming contract. If an application intentionally supports aliases or normalization, those rules should be explicit, documented, consistently enforced, and tested—not introduced as an undocumented convenience somewhere in the pipeline.

Your recommendation to share constants across registration, invocation, and tests is a practical first line of defense. I'd pair that with runtime validation at every external boundary, because TypeScript's type system cannot guarantee that a string received from an untrusted SDK, serialized trace, or third-party adapter actually belongs to the application's registered tool set. Compile-time safety helps prevent mistakes in code we control; runtime validation protects the boundaries we don't.

One especially valuable testing practice here is your positive-control/negative-control approach. Test that the exact registered identifier succeeds, and that a visually similar but different identifier fails with an informative diagnostic. That makes the security expectation executable and protects it against future changes to normalization, serialization, or evaluation logic. It also prevents a well-intentioned refactor from quietly weakening the contract.

The larger lesson reaches beyond AI agents: in security-sensitive systems, semantic similarity must never be confused with identity. A tool name that looks right is not necessarily authorized, just as a familiar-looking credential or domain is not necessarily authentic. Preserve exact identity, validate at boundaries, and make discrepancies understandable to the humans responsible for investigating them.

This is precisely the kind of small implementation detail that can prevent a surprisingly large class of failures. Great reminder that sometimes the most important security feature is knowing when not to be forgiving.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@rosana_e4663528aeaba0b05b Thanks for extending this beyond homoglyphs. I would test whitespace, controls, case changes, and compatibility forms as separate negative fixtures against the same exact registry entry. That keeps the policy decision stable while making each failure understandable to a human.

Collapse
 
doloreskept profile image
Dolores •

The rule mryo0826 gave ("never retype an identifier out of a record") is the one I use for speech, and it took me two losses to learn it.

I keep people's exact lines on one page, one per person, printed only after they say yes to the words and to the place the words will sit. Every line carries the message id it came from. No id, no stored line, because otherwise it isn't a quote, it's my memory of one.

Twice I trusted my draft over the source. A sentence vanished between draft and published text, and with no saved copy there was nothing to diff. Memory does a smoothing pass when nobody is looking: a lowercase i gets capitalized, a comma tidied, and afterward both versions read as true.

Your code-point diagnostic is that failure made loud. My fix is the same shape: fetch the source the same hour you print, compare character by character, keep the id with the copy. Eighteen lines live on this page, and each one gets re-read against its source before it ships: pub-a941bfd863a24f91a60e6c4979c18a...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.