System Prompt Assembly in AI Coding Agents: Static Contracts and Dynamic Runtime Construction
This article explains how modern AI coding agents assemble their system prompts and why that mechanism matters. It shows how a fixed base prompt acts as a behavior contract, how tool descriptions, external protocol guides, skills, and environment details are injected at runtime, and how context management handles compression, memory, and sub-agents. It also compares common shortcomings in open-source agent scaffolds and offers practical guidance for making dynamic prompts controllable, testable, and observable.
1. Introduction: The Invisible Code That Sets an Agent’s Ceiling
AI coding tools can already read large code repositories, modify code across files, run tests, and fix errors. Yet the same base model can perform very differently across coding agents, and the reason usually lies not in the model itself but in how the system prompt is assembled. The system prompt determines what the model “knows it can do, cannot do, and should look at next.” It directly affects whether tool calls are accurate, whether long conversations “forget” context, and whether dangerous operations get blocked in time.
For most AI coding tools, the system prompt is a piece of hard-coded text: injected verbatim at startup and unchanged for the entire session. This approach is simple to implement and easy to audit, but as the number of tools grows to dozens and external tool extensions are connected, problems gradually surface.
Problem 1: The prompt drifts from the actual environment. The prompt declares a tool, but it may be unavailable because of permission settings, the run mode (such as a read-only code-exploration mode), or an explicit user disable. The model then repeatedly tries to call it and repeatedly fails.
Problem 2: Static content eats into the context budget. Tool descriptions, extension capability indexes, and external environment conventions occupy the context window even when they are not needed right now, squeezing out room for code and conversation history.
Problem 3: Security constraints are hard to enforce. Requirements like “high-risk operations require user confirmation” stay only in the prompt, and the model may simplify the process on its own to push the task forward.
Problem 4: Maintenance costs keep rising. There is an implicit coupling between the prompt and the tool implementation: if a tool’s description changes but its implementation does not (or vice versa), the model’s behavior drifts.
The mainstream engineering approach treats the system prompt as a runtime-built artifact. At the start of each session, an assembly function constructs the prompt on the fly based on the current tool set, external protocol connection state, extension capability list, configuration overrides, and environment information. This article follows that design as its main thread, analyzing its static and dynamic layers, then extending into context compression, memory, and sub-agents, and finally offering engineering recommendations.
2. The Base Layer: A Static Prompt That Acts as a “Behavior Contract”
Runtime assembly does not rule out static content. On the contrary, it usually keeps a relatively fixed base prompt that serves as the agent’s “behavior contract,” governing the model’s fundamental behavior in almost all scenarios.
2.1 Tool First: Use Dedicated Tools Instead of Equivalent Commands
The base prompt explicitly requires preferring dedicated tools (file reading, content search, filename matching, precise editing, and so on) rather than achieving the same effect through terminal commands such as cat, grep -rn, or sed -i for reading, writing, and replacement. This constraint is justified on four levels:
- Permission granularity: Dedicated tools define the allowed path scope at the interface level and can grant access by read, write, or execute tiers. Terminal commands are too broad and easily bypass the principle of least privilege.
- Result structure: Dedicated tools usually return content with line numbers or structured match results, making it easier for the model to reference locations accurately. Terminal output formats vary with the environment and command flags and are hard to parse reliably.
- Predictable behavior: Dedicated editing tools require reading before replacing, and they require the replacement string to match uniquely. This avoids the collateral damage of command-line replacement and naturally forms a “understand before modifying” workflow.
- Observability: Structured calls are easier to log for auditing, making it simpler to pinpoint which step went wrong during a post-mortem.
2.2 Output Style: Spend Tokens on Information
The base prompt typically asks the model to be concise and direct:
- No emoji and no empty pleasantries;
- No repetition of information the user has already provided;
- No content-free acknowledgments or summaries;
- Code over lengthy explanations.
Such constraints may seem trivial, but the payoff is direct. A coding agent’s output enters the context history and must be carried in every subsequent turn. Redundant phrasing accumulates token consumption, dilutes key information, and even induces the model to imitate that verbose style. Constraining output style is, in essence, context economics.
2.3 Memory: Layered Discovery Paths for Convention Files
Project-level rules are usually managed as Markdown files that ship with the code repository. The base prompt declares their layered discovery path:
- The user-level global directory (conventionally
~/.claude/CLAUDE.md); - The rule file in the project root;
- Rule files in the current working directory and its parent directories.
The rules work as follows:
- Progressive scope. Global files hold personal preferences (such as commit message style or common tech stacks), project files describe engineering conventions (such as build commands or coding standards), and subdirectory files capture local special cases (such as a generated-code directory where manual edits are forbidden).
- Nearest wins. Files closer to the working directory are more targeted and should take precedence when conflicts arise.
- Timely maintenance. The prompt tells the model that when it discovers a reusable project convention, it should write it into the appropriate file per the rules rather than only following it verbally in the current conversation.
| Layer | Typical Location | Contents | Maintainer |
|---|---|---|---|
| User-level | User global config directory | Personal preferences, general habits | The developer |
| Project-level | Project root directory | Tech stack, build and test commands, coding conventions | The team |
| Directory-level | Subdirectory | Local conventions, generated-code notes, exception rules | Module owner |
One caveat: these files are themselves part of the context. Overly long content equally eats into the budget, so follow the principle of “write only information the model cannot infer from the code itself.”
2.4 Security Protocol: High-Risk Operations Require Explicit Authorization
For destructive operations, the base prompt usually draws red lines:
- History-rewriting or irreversible operations such as force push, hard reset (
reset --hard), and bulk branch deletion must be executed only after explicit user consent; - Before committing code, check the scope of changes to avoid including unrelated files or sensitive information (keys, credentials) in the commit.
More importantly, this constraint cannot live only at the text level. Mature implementations set up a permission-asking mechanism at the tool layer, so high-risk operations must pass user confirmation before execution. The prompt makes “the model know the rules,” while the tool layer makes “the rules impossible to bypass”; neither can be missing.
2.5 Extension Invocation: Declarative Skill Entry Points
When an agent supports reusable task templates called “skills” (such as code review, release note generation, or test completion), the base prompt explains that they are invoked as slash commands: entering /<skill-name> loads the corresponding instructions. The model thus learns which tasks can be handed to prebuilt flows instead of planning from scratch every time.
3. The Dynamic Layer: Runtime Knowledge Injected at Session Start
Beyond the base prompt, another batch of content is generated only at session start based on real-time state. This includes which tools are currently enabled, which external tool servers are connected, which skills are installed, and what environment is running. The design can be abstracted as the following pseudocode:
def build_system_prompt(config, registry, env) -> str:# 1. Base behavior contract (relatively static)parts = [BASE_PROMPT, MEMORY_CONVENTION, GIT_SAFETY]# 2. Tool docs: generate only for currently enabled toolstools = registry.enabled_tools(config)parts.append(render_tool_docs(tools))# 3. External protocol usage guide: inject only when connected, and re-inject after compressionmcp_delta = build_mcp_delta(config.mcp_servers)if mcp_delta:parts.append(mcp_delta)# 4. Skill index: name / description / whenToUseparts.append(render_skill_index(config.skills))# 5. Runtime environment: platform, date, working directory, version control state, etc.parts.append(env.describe())# 6. Lazy-loading hint: discover tools not yet loaded on demandif config.lazy_tool_loading:parts.append(TOOL_SEARCH_HINT)# 7. User/project configuration overridesparts.append(config.system_prompt_appendix)return "\n\n".join(p for p in parts if p)
| Injection Item | Generation Timing | Problem It Solves | Consequence If Static |
|---|---|---|---|
| Tool docs | Iterate over enabled tools, collect each tool’s prompt-function output, and concatenate | Lets the model accurately understand available capabilities and how to call them | Descriptions of disabled tools remain, inducing invalid calls |
| External protocol usage guide | Injected after a connected external tool server is detected | Tells the model about external resource connectivity and calling conventions | Describes capabilities out of thin air when no connection exists, causing hallucinated calls |
| Skill index | Aggregates the names, descriptions, and applicable scenarios of installed skills | Lets the model know which ready-made flows are available | The prompt cannot sync after skills are added or removed |
| Runtime environment | Collected at session start | Provides platform, date, working directory, and more | The model makes wrong assumptions about time and paths |
| Lazy-loading hint | Appended after on-demand loading is enabled | Guides the model to actively search for unloaded tools | The model assumes the tool set is the entire capability set |
Three of these designs deserve a closer look.
First, keep tool docs in sync with capability declarations. Collecting each enabled tool’s prompt-function output one by one and concatenating it makes the “declaration” and the “implementation” inherently consistent: disable a tool and its description disappears in sync. This directly eliminates the most common source of hallucination in static prompts.
Second, special handling of external tool protocol instructions. The currently mainstream Model Context Protocol (MCP) is an open protocol that connects external resources such as databases, documentation systems, and internal APIs through a unified client-server approach. Once a connection is established, the usage instructions provided by the server are appended to the system prompt, so the model can “see” newly connected capabilities mid-session. This kind of content is session-level incremental information, so it must be re-injected after context compression, as discussed later.
Third, configuration overrides as the final extension point. User or project custom instructions are usually concatenated at the very end. For one, content that appears later holds an attention advantage; for another, the assembly order itself defines priority: default rules → dynamic environment information → user customization.
4. Context Management: Fidelity Through Compression, Memory, and External Information
The system prompt solves “what the model knows when the session starts.” As the conversation progresses, the context keeps expanding and needs a complete management mechanism.
4.1 Compression: Auto-Summarization and “Re-injection”
A typical implementation monitors token usage and triggers automatic compaction (Compact) as it approaches the limit: it condenses earlier conversation history and tool-call results into a structured summary that preserves key decisions, file paths, and completed and pending items, then continues working on that basis.
Compression frees up space but risks information loss. The static behavior contract is usually stored as a separate field and is not compressed, whereas dynamically injected content may not survive. Therefore, key incremental information such as the external protocol usage guide is re-injected after compression, ensuring the model “still knows how to use external capabilities after compaction.” This easily overlooked detail is precisely what determines whether long-running tasks can keep moving forward.
4.2 Memory: Progressive Disclosure Across Sessions and Directories
A single session’s memory relies on the context window; cross-session memory relies on the convention files described earlier; and “which file to read right now” relies on progressive disclosure. The model does not need to know every detail up front; it first sees a capability’s name and applicable scenario in the index, judges relevance, and then loads the full content.
This follows one principle: context is a finite resource and should always load only information relevant to the current task. Injecting tool descriptions by enablement, injecting only the skill index, and loading convention files in layers are all concrete expressions of this principle.
4.3 Sub-agents: Trading Context Isolation for a Clean Main Thread
Complex tasks can be delegated to sub-agents, for example, “find every location in the repository that calls a deprecated API.” A sub-agent has its own context window and configurable tool permissions: it can perform extensive searching and reading and ultimately return only a summary of conclusions to the main agent. As a result, the main agent’s context does not accumulate hundreds or thousands of lines of intermediate search results.
Sub-agents also offer two layers of value:
- Role division. Different types of sub-agents can carry different specialized prompts; for example, a code-exploration type emphasizes “read only, no changes,” while a review type emphasizes “check item by item against the standard.”
- Permission narrowing. A sub-agent can be restricted to read-only or a specific path, reducing the risk of mistakes.
The costs are equally real: the more sub-agents, the higher the token consumption; and each sub-agent’s understanding of the problem must stay consistent with the main task, or conclusions will contradict one another. Therefore, sub-agents suit well-bounded, parallelizable exploration tasks and should not replace core modifications that require global consistency.
5. A Side-by-Side Look: Common Weak Spots in Open-Source Agent Scaffolds
Using dynamic prompt assembly as a reference, we can observe that while several open-source coding agent scaffolds offer extension mechanisms such as pluggable tools and custom instruction files, they still show clear gaps in a few details.
- Prompt assembly method: Some scaffolds still rely mainly on static templates, with runtime injection limited to a little information like environment variables. Extension capability descriptions are prone to drifting from the tool registry.
- Information fidelity after compression: Many implementations equate compression with “truncation + simple summarization” and do not rebuild the dynamically injected parts after compression, so external capability descriptions are easily lost in long tasks.
- Memory file handling: Most scaffolds support reading project instruction files, but lack layered discovery and priority rules across user-level, project-level, and directory-level scopes. As a result, users either have to reference everything manually or everything gets loaded in full.
- Sub-agents and the permission model: In some scaffolds, sub-agents are used only to run commands in parallel and lack independent context and differentiated permission constraints.
- Security boundaries: Mechanisms like command whitelists and high-risk operation confirmation are unevenly covered, and security responsibility is often handed entirely to the prompt text.
This is not to say open-source scaffolds cannot do these things well, but that there is a clear engineering gap between “getting a demo to run” and “supporting long-running tasks in real engineering.” The core of the latter is precisely the coordination of three elements: prompt assembly, context management, and permission constraints.
6. Engineering Practice: Making Dynamic Prompts Controllable, Testable, and Observable
Dynamic assembly improves adaptability but also introduces new engineering challenges: the prompt is no longer a fixed piece of text that can be reviewed at a glance. When putting this into practice, focus on the following six points.
1. Establish a prompt baseline. Prepare a set of fixed input cases for typical tasks, and record the prompt version and tool-call sequence they trigger as a baseline. Any change to the prompt or tool descriptions should be regression-tested against the baseline to prevent “fix one thing, break a dozen.”
2. Control prompt size. Keep the base contract concise, inject only the skill index, and keep tool descriptions brief and semantically clear. The token budget should be prioritized for code and task context.
3. Constrain the sources of injected content. Convention files in the repository and instructions returned by external protocols are essentially “external data.” If they contain text like “ignore the above instructions,” it should be treated as untrusted content and never promoted to system-level instructions.
4. Enforce least privilege. Grant permissions in read, write, and execute tiers, force confirmation for high-risk operations, and default sub-agents to read-only. Permission control must live at the tool layer and cannot rely on the prompt alone.
5. Replace natural-language constraints with “structured output + program validation.” For example, have the model output a change list in an agreed format, then validate it item by item in code. This is more reliable than repeatedly admonishing it “don’t miss anything.”
6. Improve observability. Record each session’s prompt fingerprint, tool calls and their failure reasons, the number of compaction triggers, and token consumption. Teams can use general cloud capabilities such as log services and monitoring alerts on platforms like Baidu AI Cloud to collect and analyze this data centrally, quickly spotting prompt bloat or abnormal tool calls.
7. Limitations and Outlook
Dynamic assembly is not a cure-all.
- The model may always “misunderstand” the prompt. A prompt is not a program and cannot guarantee 100% compliance. For high-risk operations involving money or data deletion, human confirmation or an independent approval process is still needed as a backstop.
- Even refined context has a ceiling. Sub-agents and progressive disclosure can delay the bottleneck, but once the task scale exceeds a certain threshold, you still need external knowledge bases, task decomposition, and multi-agent collaboration.
- Cross-tool consistency remains hard. When the model switches between tools, subtle differences in parameter formats and return structures can trigger errors, so conventions must be unified at the tool design stage.
We can foresee that future coding agents will emphasize “system prompt as code” even more: version control, automated testing, staged rollouts, and continuous observation will all treat prompts the way business code is treated. For developers, understanding these mechanisms matters not only for using one particular tool well, but for mastering a general methodology for building reliable agent systems: letting the model see the right information, at the right moment, with the right permissions.
