Skip to main content
Glama

BotSpot: AI Trading, Backtests and Bots

Patch a strategy file

patch_file
Destructive

Applies exact text or guarded line-range edits to one file in any strategy owned by the authenticated user and creates a new immutable strategy revision. Requires editHandle from get_file/list_files. For insert_before and insert_after operations, include an exact unique anchor. For replace_text, oldText must match exactly one location unless you explicitly select matchIndex from the returned match locations. If a statement appears in several lifecycle methods, choose the intended match and copy its compact retryOperation unchanged, or include surrounding function context. Use replaceAll=true only when every occurrence is part of the requested change; repeated text does not make unrelated resets or branches interchangeable. For a localized exact replacement, the complete required shape is {"path":"main.py","editHandle":"","operations":[{"type":"replace_text","oldText":"","newText":""}]}. Keep path, editHandle, operation type, oldText, and newText in the same call; omitting any of them fails validation. For the current attached/open strategy, omit strategyId and revisionId after get_file; the server resolves the latest conversation revision, so do not manually transcribe those UUIDs. Pass explicit ids only for a named or different strategy. For replace_range operations, include startLine and endLine. For replacing most or all of main.py after create_strategy, prefer replace_file. Do not use patch_file for a short placeholder or a repair that replaces most of the returned file. Never estimate an endLine beyond the exact returned file. For those rewrites, call replace_file directly with the complete content and latest editHandle. Before any second file mutation, read the first mutation's returned new revisionId with get_file and use that readback's revisionId and editHandle. Never reuse the preceding revisionId or editHandle after a successful mutation. For existing-strategy fixes, this is the action step after get_file identified the concrete change and returned an editHandle. Mutate only the strategy/revision named by the user when it differs from the open page context. After a successful patch, call get_file on the returned new revisionId to read back the final saved code and verify the saved executable code before final-answering; do not verify by re-reading the original/base revisionId from before the edit. When an edit follows a backtest request or result in the same conversation, validate the new saved revision with the established window, capital and data settings after readback, even when the earlier run succeeded and the customer did not repeat the test request. Explicit save-only instructions and disabled automatic-backtest preferences take precedence. A standalone file edit without a backtesting workflow is complete after saving and readback unless testing was requested. Never deploy or trade merely to validate an edit. A successful mutation, compiling/ready analysis, or readback alone does not complete the requested repair. If the saved executable code still uses the faulty causal path the user asked to repair, or new helpers/scaffolding are not connected to it, continue the remaining authorized file edits with the current editHandle. Do not final-answer with a plan, apology, model-upgrade suggestion, or admission that the repair is incomplete while authorization and execution budget permit, the file tools work, and the remaining corrective edit is known. Recover ambiguous anchors with the returned unique context, an exact guarded range, or complete replace_file; a recoverable patch-format error is not a missing capability. Finish the requested change and preserve unrelated behavior and files. For copy/apply-same-rules requests, do not use patch_file after reading only one strategy, and do not use it after reading only the target. A different revision of the named target is still target evidence, not source evidence, unless the user explicitly asked to copy from an older target revision. First read the source strategy code and the named target strategy code, then diff executable assignments/thresholds/cadence/branches within the requested copy scope. Copy only explicitly requested mechanics for a limited transfer; update every differing target value to the source value only for whole-strategy parity. Preserve target-specific identity such as symbol/ticker, strategy name, account/broker identity, and labels unless the user explicitly asks to change them; do not copy the source symbol/name into the target. Build the patch from the target file and selectively copy behavior values into it; do not patch by pasting the whole source file over the target when identities differ. In Python strategy code, self.symbol is target identity when source and target tickers differ; for a TQQQ source applied to an SQQQ target, keep self.symbol as SQQQ while copying behavior rules. Target identity does not include cadence, sleeptime, trigger thresholds, order sizing, entry/exit branches, helper calls, or risk rules; those are behavior and must match the source only when included in the requested copy scope. Do not add settings absent from the source or merge unrelated memory/preferences. Before patch_file in a copy/apply-same-rules edit, preserve the literal target identity line from the target readback in the patch. If your patch would turn target identity into source identity, do not call this tool yet; correct the patch first. After readback for a copy/apply-same-rules edit, if the target file contains source identity such as the source symbol/name/account/broker, edit again before final-answering. Do not list source identity as evidence of success. When the fix replaces an executable setting, guard, helper call, order path, or branch, remove or replace the stale executable code; do not append a competing line and leave the old contradictory behavior in place. When the user says to stop using a value/source, or says that value/source is stale or wrong, remove executable fallback uses of that value/source instead of keeping them as a backup path. If the readback still contains the stale executable value/source/fallback the user asked to remove, the edit is not complete; call patch_file or replace_file again before final-answering. If the user supplied a concrete replacement value for a code-owned setting such as cost basis, entry price, threshold, cadence, market, symbol, or helper path, replace the stale executable literal/path and read it back. For live fill/cost-basis fixes where live order tools fail but the user supplied a concrete bot-owned fill, record/use that exact fill value in executable state/code as the bootstrap latest verified bot-owned fill; do not add only an unset placeholder such as None. For plan-driven first-build work, make the visible implementation item in_progress with update_plan_item before using file tools so the user sees the current plan step while file work runs. If a patch operation fails, no new revision was created: read the current file/editHandle and retry with replace_file or a corrected patch before starting a backtest or ending the strategy build. Default to the active strategy unless the user explicitly asks for another owned strategy.

Tool call template

Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.

{
  "id": 1,
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "arguments": {
      "path": "<path>",
      "editHandle": "<editHandle>",
      "operations": "<operations>"
    },
    "name": "patch_file"
  }
}

Input Schema

NameRequiredDescriptionDefault
pathYes
editHandleYesOpaque edit handle returned by list_files or get_file. It replaces raw hash copying while preserving stale-write protection.
operationsYes
revisionIdNoBase revision ID to snapshot from. Omit with strategyId for the current attached/open strategy.
strategyIdNoBase strategy id. Omit with revisionId for the current attached/open strategy so UUIDs do not need to be transcribed.
descriptionNoShown to the customer as "How your strategy works". One or two plain sentences on what the strategy now does, e.g. "Buys Apple after a 5% drop in a day and sells at a 10% gain." Write for the customer, not an internal change note.

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed1 schema field changed
    • addedInput schema / properties / description / description
      Added value: +"Shown to the customer as \"How your strategy works\". One or two plain sentences on what the strategy now does, e.g. \"Buys Apple after a 5% drop in a day and sells at a 10% gain.\" Write for the customer, not an internal change note."
  2. Changed3 schema fields changed
    • addedInput schema / properties / operations / items / properties / matchIndex
      Added value: +{
      +  "description": "For replace_text only: zero-based index of the exact oldText occurrence in the working content before this operation. Select it explicitly from an ambiguity result matches[].matchIndex, or use its retryOperation unchanged. Cannot be combined with replaceAll=true.",
      +  "minimum": 0,
      +  "type": "integer"
      +}
    • changedInput schema / properties / operations / items / properties / oldText / description
      Previous value: -"Literal unique exact block copied from the current get_file readback, including indentation and surrounding function or branch context. A repeated statement alone is ambiguous."New value: +"Literal exact block copied from the current get_file readback, including indentation. A repeated statement requires an explicitly selected matchIndex or surrounding unique function/branch context."
    • changedInput schema / properties / operations / items / properties / replaceAll / description
      Previous value: -"True only when the requested change applies to every occurrence; not an ambiguity workaround. For a narrow edit, expand oldText with unique context instead."New value: +"True only when the requested change applies to every occurrence; not an ambiguity workaround. For a narrow edit, select matchIndex from the returned matches or expand oldText with unique context."
  3. First observed

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare destructiveHint=true, idempotentHint=false, and readOnlyHint=false, so the description's job is to add context — and it does: immutable revision creation on success, 'If a patch operation fails, no new revision was created', stale-write protection via editHandle, ambiguity results exposing matches[]/retryOperation, and the mandate to read back the new revisionId. It does not describe rate limits, permission/ownership enforcement beyond 'owned by the authenticated user', or the response shape, and much of the text is agent workflow policy rather than tool behavior, so it stops short of a 5.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness2/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The first sentence is well front-loaded, but the body is a multi-hundred-word wall mixing schema guidance, JSON examples, copy/apply-same-rules policy, live-fill bootstrapping, plan-item updates, and anti-apology directives. Large stretches repeat the same rules (editHandle/revisionId reuse, identity preservation, readback verification) and would be far more usable as a short core plus references to get_file/replace_file.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a destructive, non-idempotent mutation with six parameters and no output schema, the definition covers the critical ground: prerequisites (editHandle from get_file/list_files), failure semantics, ambiguity recovery, revision chaining, and the required readback. What it does not cover is the actual success response shape (new revisionId, match locations) beyond passing mentions, and the 'description' parameter is left unexplained.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 67% schema coverage, the description meaningfully supplements the schema: oldText must match exactly one location unless matchIndex is selected from returned matches, anchor must be unique and include function/branch context for insert_before/insert_after, replaceAll=true only when every occurrence is intended, startLine/endLine are required for replace_range, and strategyId/revisionId may be omitted together for the current strategy. The 'description' parameter (customer-facing 'How your strategy works') is never mentioned in the description at all.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The opening sentence names a specific verb and resource — 'Applies exact text or guarded line-range edits to one file in any strategy ... and creates a new immutable strategy revision' — which tells an agent both the action and its side effect. It also explicitly distinguishes itself from the sibling replace_file ('prefer replace_file' for whole-file rewrites, 'Do not use patch_file for a short placeholder or a repair that replaces most of the returned file'). An agent can separate the two tools without opening either schema.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Guidance is unusually explicit about when to use, when not to use, and what to use instead: patch_file for localized exact edits, replace_file for full-file rewrites or placeholder repair, omit strategyId/revisionId for the open strategy but pass explicit ids for a named strategy, and read source plus target before a copy/apply-same-rules edit. It even covers the sequencing rule that a second mutation must use the readback revisionId/editHandle from the first.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Try in Browser

Glama MCP Gateway

Add one secure layer between your agents and this server.