Server-Side AI Agent Architecture: How to Choose a Stack and Implement Core Capabilities

    This article explains how to evaluate and build server-side AI agents beyond simple chat systems. It defines the engineering boundaries of an agent, proposes a six-layer controlled-execution architecture, and details the core capabilities needed for production: layered memory persistence, recoverable long-running task scheduling with idempotency, dynamic capability packages, standardized tool integration with governance, and sandboxed code execution. It closes with a set of evaluation dimensions and a phased rollout strategy, arguing that identity, permissions, state, execution boundaries, and auditing must live in reliable engineering mechanisms rather than in the model itself.

    1. Before Choosing a Stack, Define the Engineering Boundaries of an Agent

    When facing different server-side agent solutions, developers often ask first, “Which framework is easier to use?” But that question only becomes meaningful alongside business constraints. An assistant that answers internal knowledge questions has very different infrastructure needs from an agent that continuously handles tasks, calls external tools, and executes code.

    A basic conversational system is usually built around a single request: receive input, assemble context, call the model, and return a result. An agent, by contrast, must maintain state across multiple steps, decide the next action based on execution results, and handle waiting, failure, cancellation, and recovery. Its core difficulty is not getting the model to call a few more tools, but keeping the entire execution process controllable in a real environment.

    So selection should start from these questions:

    • Does the task need to run continuously across requests and across processes?
    • Does historical information need to be stored long-term and used for future decisions?
    • Are tools provided by multiple teams, and do they need to be integrated dynamically?
    • Is executing model-generated code allowed?
    • Which operations require user approval, and which must be prohibited?
    • After a restart, timeout, or duplicate delivery, how do you avoid producing duplicate side effects?

    These questions determine the system architecture. Ease of model integration matters, but it cannot replace an assessment of lifecycle, security boundaries, and operational capability.

    2. Design the Agent as a Controlled Execution System

    It is recommended to divide the overall architecture into six parts:

    1. Access and identity layer: handles authentication, tenant identification, request validation, and rate limiting.
    2. Orchestration layer: manages task state, execution steps, budget, and termination conditions.
    3. Memory layer: stores conversation history, task state, and confirmed long-term information.
    4. Capability layer: provides capability packages and a tool catalog that can be assembled per request.
    5. Execution layer: handles external tool calls, asynchronous tasks, and isolated code execution.
    6. Governance layer: centrally performs permission checks, auditing, metrics collection, and anomaly alerting.

    A single task can run along the following path:

    Receive request → create task record → load relevant memory → select capabilities and tools → generate the next action → validate permissions → execute → persist the result → continue or finish.

    The most important principle here is: the model proposes actions, while the server decides whether an action is allowed, how it is executed, and how it is recorded.

    Model output must not become the basis for permissions directly. Any action involving file writes, message sending, resource modification, or code execution should go through independent server-side validation. Even if the prompt explicitly requires the model to follow rules, these controls cannot be skipped.

    3. Memory Management: From Context Window to Layered Persistence

    3.1 Store conversation history, task state, and long-term memory separately

    Simply using an in-memory window to hold the last several turns of conversation is fine for quick validation, but it struggles to support long-running tasks. A process restart loses information, and after horizontal scaling, session state can become inconsistent.

    A more robust approach is to distinguish three types of data:

    Conversation history stores user input, model replies, tool calls, and results, and is mainly used to reconstruct the interaction.

    Task state stores the current step, wait conditions, execution results, and failure reasons, and is the basis for task recovery.

    Long-term memory stores information that can be reused across sessions, such as preferences the user has explicitly confirmed, stable business constraints, and verified conclusions.

    The three cannot substitute for one another. A conversation summary may omit key parameters, so it should not be the sole basis for high-risk actions such as executing payments or sending notifications; nor should tool output be turned into a long-term fact without verification.

    3.2 File-based memory is fine to start with, but its limits must be stated

    File persistence is intuitive to implement, easy to inspect and export, and suitable for early-stage systems with a single node and low concurrency. You can organize it in layers by tenant, user, and session, storing event records, summaries, and long-term entries separately.

    But “writing to a file” does not equal reliable persistence. You still need to handle:

    • Concurrent writes and file locking;
    • Incomplete records caused by interrupted writes;
    • Validity checks on file names and paths;
    • File permissions and protection of sensitive information;
    • Backup, deletion, and recovery;
    • Data consistency across multiple instances.

    For task state that requires concurrent modification across multiple nodes, you should generally use persistent storage that supports transactions or conditional updates. Files can continue to serve archiving, export, or storage of large results, but should not act as a distributed state-coordination mechanism without evaluation.

    3.3 Long-term memory should retain source and validity

    Each long-term memory entry should contain at least the content, source, creation time, applicable scope, and status. For information that may change, you should also set an expiration or re-confirmation mechanism.

    Memory writes can follow a flow of “candidate extraction → rule validation → human confirmation when necessary → formal save.” For sensitive content such as contact details, account information, or authorization scope, you should not automatically create long-term records based solely on model inference.

    When retrieving memory, you should also control the context size: prioritize loading entries relevant to the current task, combined with recent interactions and necessary summaries, rather than putting all history into the prompt. This both reduces cost and limits the interference of stale or irrelevant content on decisions.

    4. Long-Running Task Scheduling: Turn Future Actions into Recoverable Tasks

    4.1 Tasks must exist independently of the current request

    “Run later,” “check every day,” and “notify when a condition is met” cannot rely on a request thread waiting continuously. The task definition should be persisted, with a scheduling mechanism triggering execution at the appropriate time.

    A task record can contain the following common fields:

    1. Task identifier
    2. Owning tenant and initiating user
    3. Trigger method and expected execution time
    4. Time zone
    5. Task status and status version
    6. Input parameter snapshot
    7. Capability package version
    8. Retry policy
    9. Creation time and update time

    One-time, fixed-interval, and calendar-rule-based tasks each require separate consideration of time semantics. In cross-time-zone scenarios in particular, be explicit about which time zone is used, how daylight saving changes are handled, and whether missed tasks are executed after the service resumes.

    4.2 Use a state machine to express the execution lifecycle

    Task states can be divided into pending, running, awaiting approval, awaiting an external result, succeeded, failed, and cancelled. State transitions should be controlled by the server, not freely modified by the model.

    Long tasks should be split into recoverable steps, with checkpoints saved at step boundaries. On recovery, first determine which steps are complete and which operations have already produced side effects, then decide whether to continue, avoiding a full rerun from the start.

    Periodic tasks should also distinguish between the “schedule definition” and a “single execution instance.” Only then can you correctly handle a failed single run, overlapping adjacent runs, and pausing the schedule as a whole.

    4.3 Retries must be paired with idempotency design

    A network timeout does not mean the operation did not succeed. An external service may have already completed processing and only failed to return the response. Retrying directly could send a message twice or create a business record twice.

    Therefore, operations with side effects should use a stable business idempotency key and store the association between the request and the result. If an external interface does not support idempotency, you should reduce duplication risk through business queries, reconciliation, or human confirmation.

    Retry policies should also distinguish transient from permanent failures. Temporary connection failures can be retried a limited number of times; insufficient permissions, invalid parameters, or nonexistent resources should generally stop automatic retries. All retries need caps on count, time, and cost.

    5. Dynamic Capability Packages: Hot-Pluggability Must Not Bypass Permission Governance

    A capability package can combine the instructions, prompt templates, input constraints, tool list, and resource configuration needed for a certain class of tasks. Its value is loading on demand, giving different tasks different capability sets rather than always exposing all tools to the model.

    A capability package should clearly describe:

    • Applicable tasks and non-applicable scenarios;
    • Required tools and permissions;
    • Inputs, outputs, and preconditions;
    • Timeouts and resource budgets;
    • Involved risks and approval requirements;
    • Version and dependencies.

    5.1 Assemble per request, version per execution

    Dynamic loading should not mean arbitrary changes to global configuration. The server should generate a capability snapshot for this execution based on the current user identity, tenant policy, and task type.

    Once a task starts, the capability package version in use should be fixed. New versions affect subsequent tasks by default; whether a running task switches requires an explicit migration rule. Otherwise, if tool definitions or behavior constraints change midway through a task, recovery and auditing become difficult.

    5.2 Capability descriptions are input, not a security control

    Text in a capability package may come from external maintainers and may contain untrusted instructions. So it cannot override system rules or gain extra permissions.

    The real limits should be enforced at the execution layer: tool whitelists, resource access scope, credential isolation, call-rate limits, and approval mechanisms. Even if the model proposes an action beyond the capability scope, the server should reject it.

    6. Standardized Tool Integration: Governance Is Still Needed After Protocol Unification

    Integrating tools through a standardized protocol can reduce the cost of repeatedly adapting to various external services. But unifying the protocol only solves communication and description; it does not automatically solve security, trustworthiness, and stability.

    6.1 Tool registration should be validated

    The dynamic registration flow should include at least: confirming the service source, validating the connection configuration, checking the tool description, assessing permission requirements, running a health check, and finally publishing the tool to the visible catalog of a specified tenant or user.

    You cannot let ordinary users submit arbitrary network addresses for the server to connect to directly. You must restrict the accessible address range to prevent access to internal management interfaces or other protected resources.

    Tool updates also need version management. When the input structure changes, complete compatibility validation first, so that tasks already queued do not suddenly fail to call the tool at execution time.

    6.2 Tool output must not be promoted directly to trusted instructions

    Data returned by tools may contain errors, sensitive information, or inducement text. The server should validate the structure, limit the size, and redact at appropriate points.

    When external content demands “ignore the rules,” “call another tool,” or “read hidden credentials,” treat it as text within the data, not as a new authorization. The system must preserve the boundary between external information and internal control instructions.

    6.3 Lifecycle management cannot be missing

    Dynamic integration also means dynamic exit. When a tool service becomes unavailable, a certificate changes, authorization is revoked, or the protocol becomes incompatible, you should be able to stop new calls, handle in-flight requests, and release connection resources.

    For tools that fail repeatedly, you can temporarily stop automatic calls and return a clear degraded result to the task, preventing the agent from falling into a meaningless retry loop.

    7. Sandboxed Code Execution: Isolation Is the Baseline, Not a Security Guarantee

    Code execution can extend an agent’s data-processing capabilities, such as analyzing spreadsheets, generating charts, and converting files. But model-generated code must be treated as untrusted code and cannot run directly in the business service process.

    7.1 The execution environment should have clear boundaries

    Each execution unit should use an independent working directory and limit processor time, memory, runtime, output size, and process count as needed. By default, do not allow access to sensitive host paths, do not grant high privileges, and do not inject the full credentials used by the business service.

    Network access should be off by default; when genuinely needed, open only approved targets. User-input files should be mounted in a restricted way, and output files should be writable only to a designated area.

    Containers can provide practical isolation, but they do not inherently form a complete security boundary suitable for all threat models. High-risk, multi-tenant scenarios also require stronger isolation methods, host protection, and a continuous update mechanism.

    7.2 Separate submission, execution, and artifact management

    The recommended flow is:

    Code and input validation → create isolated environment → inject minimal input → restricted execution → collect results → inspect output artifacts → destroy the environment.

    Static code checks can only serve as an auxiliary measure and cannot replace runtime isolation. After execution, also limit log length, check output paths, prevent oversized files from exhausting storage, and ensure resources are still reclaimed on timeout or abnormal exit.

    7.3 Avoid infinite repair loops

    An agent can attempt to fix code based on execution errors, but you should limit the number of repairs, total runtime, and cumulative resource consumption. For security constraints such as permission denials or network prohibitions, it should not try to bypass them by repeatedly rewriting code.

    When presenting results, also distinguish “the program ran successfully” from “the business conclusion is correct.” A statistics script exiting normally does not prove that the data scope, calculation method, or inferred conclusion is sound.

    8. How to Evaluate a Server-Side Agent Solution

    Selection should revolve around verifiable questions, not just comparing the number of examples or the interface style.

    Focus on the following dimensions:

    Model adaptability: Is it easy to switch models, and can it clearly handle structured output, streaming results, and tool-call exceptions?

    State and recovery capability: Can it persist task state, and does it support checkpoints, cancellation, concurrency control, and failure recovery?

    Tool governance capability: Can it filter tools by identity, and does it support version management, approval, and controlled dynamic registration?

    Security boundaries: Are permissions enforced by the server, are memory and external data isolated, and does code execution have resource limits?

    Observability: Can it correlate tasks, steps, model requests, and tool calls, and can it locate latency, cost, and failure causes?

    Maintenance cost: Are core flows easy to test, are extension points clear, and do upgrades affect existing tasks?

    Validation should cover exception paths: process restarts, duplicate tasks, tool timeouts, authorization revocation, capability package updates, malicious input, and sandbox resource exhaustion. Completing a demo does not mean a solution can reliably handle production tasks.

    9. Phased Rollout Is More Reliable Than Building Everything at Once

    In the first phase, build a minimal closed loop: model calls, a few controlled tools, session persistence, and complete auditing, and first define how failures are reported.

    In the second phase, introduce the task state machine, background scheduling, idempotency, and recovery capability, so tasks no longer depend on the current connection staying alive.

    In the third phase, build dynamic capability packages and a tool catalog, and refine tenant isolation, version snapshots, and approval mechanisms.

    In the fourth phase, integrate the code sandbox, gradually open network, file, and resource permissions, and validate boundaries through fault testing.

    Ultimately, choosing a server-side agent is not about finding a framework that can handle every capability, but about deciding which capabilities the framework provides and which controls the business system must own. The model can handle planning and reasoning, but identity, permissions, state, execution boundaries, and auditing must rest in reliable engineering mechanisms. Only when these foundational loops hold can an agent move from a demo feature to a sustainably running service.