How AI Coding Agents Work at Runtime: Prompts, Context, and Tool Governance

    This article breaks down the runtime mechanisms behind modern AI coding agents built on large language models (LLMs). It covers how system prompts are assembled dynamically at runtime, how context windows are managed and compacted, how sub-agent architectures isolate tasks, how external tools are connected through the Model Context Protocol (MCP), and how tool calls are governed. It also compares the design trade-offs of different open-source agent scaffolds and summarizes practical best practices for enterprise adoption.

    How AI Coding Agents Work at Runtime: A Breakdown of Core Mechanisms

    In modern software development, LLM-based AI coding assistants have evolved from simple code completion tools into agent systems capable of planning tasks autonomously, calling tools, and modifying codebases. However, as the number of interaction turns grows and toolchains become more complex, engineering challenges such as context window bloat, conflicting instructions, and rigid system prompts become increasingly prominent.

    This article takes a deep look at the core implementation mechanisms of modern AI coding agents, including dynamic system prompt assembly, context management, sub-agent architecture, external protocol extensions such as MCP, and tool-call governance. It also compares the design philosophies of different open-source agent scaffolds from an engineering perspective and distills a set of actionable best practices for building agents.


    1. Dynamic Assembly of the System Prompt

    1.1 From Static Injection to Runtime Construction

    Early AI coding tools typically hard-coded the system prompt as a static string that stayed unchanged throughout the session lifecycle. This approach has clear limitations: when the available toolset changes or the runtime environment switches, a static prompt cannot update the model’s understanding in time.

    Modern agent architectures adopt a runtime dynamic assembly strategy. In a typical implementation, the system synthesizes the final prompt on the fly through a dedicated build function (such as buildEffectiveSystemPrompt) each time a session is initialized. This design keeps the model’s perceived “world” strictly consistent with the actual runtime environment, the connected resources, and the user’s personalized configuration.

    1.2 The Core Behavioral Contract

    A default system prompt should be more than a role definition; it should be treated as a strict behavioral contract. A high-quality contract typically includes the following core constraints:

    • Tool-First Policy: The model must be explicitly required to call structured, dedicated tools (such as Read, Grep, and Glob) for tasks like reading files or searching code, rather than relying directly on basic shell commands. Dedicated tools not only provide more standardized JSON output that is easier for the model to parse, but more importantly offer finer-grained permission control that helps prevent accidental operations.
    • Output Constraints: To improve token efficiency and reduce noise, the prompt should require concise, direct output and prohibit emojis, filler modifiers, and unnecessary acknowledgments (such as “Sure, I will…”).
    • Safety Protocols: For high-risk operations, the system must draw clear red lines in the prompt. For irreversible operations such as force push, reset --hard, or database deletion, the model must be trained to request explicit authorization from the user upon recognizing such instructions rather than executing them directly.
    • Memory Guidance: The model should be told how to automatically discover and follow the rules in memory files (such as CLAUDE.md or similar configuration files). Path lookup typically follows a hierarchical override logic of “user global directory -> project root -> current subdirectory,” ensuring that local rules can override global ones.

    1.3 Runtime Injection

    Beyond the base contract, the following dynamic content should be concatenated into the prompt in real time during each session:

    1. Dynamic assembly of tool descriptions: The system iterates over the prompt() method of every currently enabled tool and embeds each tool’s detailed description dynamically. This means that if an administrator disables a tool, its description automatically disappears from the prompt, avoiding “hallucinated calls.”
    2. Environment context enrichment: Logic similar to enhanceSystemPromptWithEnvDetails() injects information such as the current platform (OS), system date, and working directory (CWD), giving the model basic environment awareness.
    3. External protocol instructions: When external servers are connected through standard protocols such as MCP (Model Context Protocol), usage instructions are injected as a delta attachment. Notably, after context compaction, these instructions need to be re-injected so the model does not forget how to call external tools.

    2. Context Management Strategies

    2.1 Context Window Bloat and Governance

    The agent’s context window is an extremely valuable and limited resource. As the conversation progresses, files are read, and tool results accumulate, token consumption rises quickly. Without effective governance, the agent not only risks hitting the model’s context limit but also suffers from the “Lost in the Middle” phenomenon, where the model’s attention to information in the middle of the context drops significantly.

    2.2 Sliding Window and Intelligent Compaction

    To address these issues, the industry commonly adopts a context compaction strategy. When token usage reaches a threshold (typically a certain percentage of the maximum window, such as 80%), the system triggers the compaction flow:

    • Summary generation: The system uses the LLM’s own capabilities to summarize early conversation history, completed subtasks, and old tool call results.
    • Retaining recent details: Compaction usually preserves the verbatim details of the most recent few turns and only abstracts earlier history, freeing up token space while maintaining task continuity.
    • Re-injection mechanism: After compaction, the system must ensure that key “contract” content (such as the system prompt and the currently enabled tool list) is re-injected into the context to prevent instruction loss caused by compaction.

    2.3 Externalizing File State with Git Tracking

    To ensure the traceability of code changes, modern agents should automatically take snapshot backups through a version control system (such as Git) before modifying files. This mechanism stores the real state of files in external version history rather than relying solely on textual descriptions in the context. It not only saves a large amount of tokens (no need to keep the full file history in context) but also provides a solid foundation for code review and rollback.


    3. Sub-Agent Architecture and Task Isolation

    3.1 Collaboration Between the Main Agent and Sub-Agents

    When handling complex tasks (such as “refactor the entire authentication module”), processing all details in the main conversation can easily overflow the main context. Advanced architectures therefore introduce the concept of a sub-agent.

    • Task delegation: The main agent handles high-level planning. When it encounters tasks that require extensive exploration or independent subtasks, it delegates them to a dedicated sub-agent.
    • Context isolation: Each sub-agent has an independent context window. It does not need the full history of the main conversation and only receives the task description passed by the main agent. This isolation effectively prevents irrelevant information from polluting the main context.
    • Result refinement: After finishing execution, a sub-agent returns only refined results (such as the list of modified files or a summary of discovered errors) to the main agent, rather than sending back all intermediate debugging output (such as large amounts of grep output).

    3.2 Parallel Processing and Concurrency Control

    By design, the sub-agent mechanism naturally supports parallel processing. For example, the main agent can dispatch three subtasks at the same time: one for frontend code refactoring, one for backend API updates, and one for writing unit tests. This “divide and conquer” strategy greatly improves the execution efficiency of complex tasks.


    4. External Protocol Extensions (MCP) and Tool Governance

    4.1 MCP: Standardized Access to External Capabilities

    As an open protocol standard, the Model Context Protocol (MCP) aims to solve the problem of standardized connections between LLMs and external data sources and tools. With MCP, agents can seamlessly connect to external resources such as databases, API gateways, and file systems without writing hard-coded adapters for each specific system.

    4.2 Robust Tool-Call Design

    In real operation, tool call failures are inevitable. A robust agent system should have comprehensive error handling and retry mechanisms:

    • Structured error feedback: When a tool call fails (due to invalid parameters, insufficient permissions, a timeout, etc.), the system should feed structured error information back to the LLM rather than just returning a generic error code. This allows the LLM to understand the cause of the failure and decide autonomously whether to fix the parameters and retry or report the blocker to the user.
    • Permission sandbox: All tool calls should execute within a strict permission sandbox. For write operations that involve system modifications, a strict user approval flow must be enforced to ensure that users retain final control over the agent’s behavior.

    5. Comparative Analysis: Design Trade-offs of Open-Source Scaffolds

    By comparing the source code and architecture of current mainstream open-source agent scaffolds, we can observe significant differences in design philosophy across teams.

    5.1 Granularity of Mechanism Handling

    Some open-source frameworks excel in the granularity of their mechanism handling. For example, they tend to have more rigorous engineering implementations for prompt re-injection after context compaction, dynamic assembly of tool descriptions, and context isolation for sub-agents. In contrast, some earlier open-source frameworks may adopt a simpler static prompt strategy; while this lowers the development barrier, its stability and token efficiency are often somewhat inferior when facing complex, long-running tasks.

    5.2 The Trade-off Between Extensibility and Closure

    • Highly extensible architecture: Tends to provide a comprehensive plugin system, MCP protocol support, and custom sub-agent capabilities, making it suitable for building enterprise-grade complex workflows.
    • Lightweight closed architecture: Tends to be ready out of the box, with a fixed built-in toolset and workflow, making it suitable for rapid prototyping or vertical applications in specific scenarios.

    6. Enterprise Adoption Recommendations and Best Practices

    For enterprises and development teams looking to build or adopt AI coding assistants, the following recommendations are proposed based on the analysis above:

    1. Prioritize a dynamic prompt architecture: Avoid hard-coding business rules in a static prompt. Environment information, the tool list, and safety protocols should be treated as dynamic components assembled in real time at runtime, ensuring the agent’s behavior adapts to its environment.
    2. Establish an approval flow for tool calls: For all high-risk tool calls involving production environments, database modifications, or file deletion, a mandatory user approval step must be established to keep human developers firmly in the loop.
    3. Leverage cloud-native capabilities to improve robustness: When deploying agent services internally, enterprises can combine general cloud product capabilities such as container services, object storage, log services, and monitoring and alerting to achieve elastic scaling of the agent runtime environment, full auditing of execution logs, and real-time alerting on abnormal states, ensuring production-grade availability.
    4. Continuously iterate on memory and knowledge bases: Regularly review and optimize the project’s memory files and knowledge base to ensure the agent can accurately access the latest architectural decisions, coding standards, and domain knowledge, reducing incorrect generation caused by stale knowledge.

    Conclusion

    The evolution of AI coding assistants is essentially a history of the progress of context engineering and tool governance. From static prompts to dynamic assembly, from a single conversation to sub-agent collaboration, and from a closed toolset to the standardized MCP protocol, every mechanism refinement aims to maximize the agent’s reasoning capability and task execution reliability within limited compute and context windows. A deep understanding of these underlying mechanisms will help developers build truly efficient, safe, and intelligent development workflows in the coming wave of AI-assisted development.