Java and Domain-Driven Design: Building an Extensible AI Agent Tool Orchestration Framework

    Moving an AI Agent from a demo to production requires more than a model-and-function loop. This article explains how to use Java and Domain-Driven Design (DDD) to build an extensible tool orchestration framework. It covers layered architecture, bounded contexts, unified tool contracts, execution pipelines, remote protocol and in-process plugin extensions, aggregates, domain events, security, approvals, concurrency, observability, testing, and a phased implementation roadmap.

    Java and Domain-Driven Design: Building an Extensible AI Agent Tool Orchestration Framework

    1. From Demo to Production: The Real Engineering Challenges of Agents

    During the demo stage, an LLM-powered Agent often needs only a simple loop:

    1. The model reasons.
    2. It selects a tool.
    3. The system returns an observation.
    4. The model continues reasoning.

    This loop can be implemented in a few hundred lines of code, which easily creates the impression that an Agent is simply “calling a model and invoking functions.” Once the system enters a real business environment, however, the limitations quickly become visible.

    First, the toolset grows rapidly. A system may start with three or five tools and grow to dozens within six months: file operations, directory search, command execution, persistent terminal sessions, sub-agent creation, background jobs, and web content retrieval. Each tool has its own parameter structure, return format, timeout requirements, and side-effect level. Without a unified contract, callers must rely on extensive branching logic, and the codebase quickly becomes difficult to maintain.

    Second, state begins to overlap. A single conversation may contain message history, tool-call records, pending approval requests, background task handles, and temporary file references. These states have different lifecycles. Putting everything into one context object soon leads to concurrent modification, serialization failures, and inconsistent state.

    Third, extension requirements appear constantly. Different teams may want to provide tools as independently deployed services or as deeply integrated in-process plugins. Some tools may be implemented in other languages, while others may require extremely low latency. Without explicit extension points, every integration requires changes to the core codebase.

    Fourth, security and governance cannot be postponed. Command execution, file writes, and network access are high-risk capabilities. They require permission checks, sandbox isolation, human approval, and audit trails. A demo can sometimes prioritize getting the flow working, but in production, any missing control can become an incident entry point.

    Finally, observability requirements increase sharply. A single conversation may trigger a dozen tool calls across multiple modules. When something fails, operators need to answer several questions quickly: Which step failed? What was the input? What did the model see? Where was time spent? How much did the operation cost?

    These problems are not primarily caused by insufficient model capability. They arise because the engineering structure has not kept pace. A maintainable Agent framework must answer four questions:

    • How are tools described and discovered consistently?
    • How should domain boundaries be defined to prevent tangled logic?
    • How can extension points support both in-process and cross-language implementations?
    • How can execution be observable, auditable, and reversible where necessary?

    This article uses Java and Domain-Driven Design (DDD) as the technical foundation for discussing an extensible Agent tool orchestration framework. The design is based on engineering practices involving more than 20 built-in tools and more than 20 domain modules. The code examples are illustrative; the focus is on structure and contracts rather than implementation details.

    2. Overall Architecture: Four Layers and Bounded Contexts

    2.1 Four Responsibilities

    The architecture can be divided into four layers. Each layer depends only on the layer below it, avoiding reverse coupling.

    The interface layer handles protocol adaptation and entry points, including HTTP APIs, command-line interfaces, message-event consumers, and scheduled triggers. It does not make business decisions. Its responsibility is to convert external requests into application-layer commands.

    The application layer coordinates use cases. Processing a user message, decomposing a task, and executing a batch of tool calls are all application services. The application layer contains no domain rules. It coordinates domain objects and infrastructure capabilities to complete a use case.

    The domain layer is the core of the framework. It contains bounded contexts for conversations, messages, tool calls, tasks, memory, approvals, quotas, and auditing. Each context has its own aggregate roots, entities, value objects, and domain services. The domain layer does not depend on any specific storage or network implementation.

    The infrastructure layer provides technical capabilities such as model clients, persistence implementations, object storage, message queues, sandbox environments, logging, and metrics reporting. Infrastructure implements the ports defined by the domain layer, applying dependency inversion.

    2.2 Defining Bounded Contexts

    When more than 20 domain modules are placed side by side, the resulting dependency graph quickly becomes difficult to maintain. Grouping modules by business capability produces a smaller set of bounded contexts:

    • Conversation context: conversation aggregates, message sequences, and context-window policies.
    • Tool context: tool contracts, the tool registry, and tool-call records.
    • Task context: background-task aggregates, task state machines, cancellation, and timeouts.
    • Memory context: long-term memory entries, retrieval strategies, and summary compression.
    • Approval context: approval requests, approval decisions, and timeout fallback behavior.
    • Quota and audit context: tenant quotas, usage metering, and audit events.
    • Extension context: remote protocol adapters, plugin lifecycle management, and version negotiation.

    Three principles guide the boundaries:

    1. Split by business capability rather than by technical layer.
    2. Place modules with similar rates of change together.
    3. Give each context clear ownership and external contracts.

    Cross-context collaboration should primarily use domain events, followed by application-layer orchestration. One bounded context should not directly modify another context’s aggregates.

    3. The Tool System: A Unified Contract Enables Extension

    3.1 Essential Elements of a Tool Contract

    As the number of tools increases, the most dangerous pattern is for every tool to behave differently. A unified contract should describe at least five categories of information:

    • Identity: name, version, and description
    • Input and output structures
    • Side-effect level
    • Execution constraints: timeout, idempotency, and parallel execution
    • Required permissions

    An illustrative interface is shown below:

    1. public interface Tool<I, O> {
    2. ToolSpec spec();
    3. O execute(I input, ToolContext context) throws ToolException;
    4. }
    5. public record ToolSpec(
    6. String name,
    7. String version,
    8. String description,
    9. String inputSchema, // Parameter structure description
    10. String outputSchema, // Return structure description
    11. SideEffect sideEffect, // NONE / READ / WRITE / DESTRUCTIVE
    12. boolean idempotent,
    13. boolean parallelizable,
    14. Duration timeout,
    15. Set<String> requiredPermissions
    16. ) {}

    The side-effect level is particularly important. Read-only tools can usually run in parallel, be cached, and be retried at a relatively low cost. Destructive tools must be serialized, require approval, and produce complete audit records. Once side effects are included in the contract, the orchestrator can make correct scheduling decisions instead of relying on informal agreements.

    3.2 Categories of Built-In Tools

    Built-in tools can generally be grouped into five categories.

    File operations include reading, writing, appending, directory listing, content search, and metadata queries. Path normalization and allowlist validation are essential to prevent access outside the permitted workspace.

    Command-line and terminal tools include one-time command execution, persistent sessions, standard-output truncation, and exit-code handling. Their main concerns are sandbox isolation, command allowlists, and execution time limits.

    Sub-agent tools support spawning, waiting, result aggregation, and failure cancellation. A sub-agent delegates part of the reasoning responsibility and therefore must be protected against unlimited recursive spawning.

    Background task tools support submission, status queries, result retrieval, and cancellation. Unlike foreground calls, background tasks live across multiple requests and require an independent state machine and persistence model.

    Network access tools support content retrieval, structured extraction, and result truncation. Domain allowlists, response-size limits, timeouts, and fallback behavior are essential.

    Every tool category should use a consistent error model. Tool failures are normal rather than exceptional: invalid parameters, insufficient permissions, missing targets, timeouts, and unavailable downstream services are all expected conditions. The error model must distinguish retryable from non-retryable failures and return structured error information to the orchestrator, giving the model an opportunity to correct its behavior.

    3.3 Registration and Discovery

    A tool registry can organize tools by namespace and support filtering by tags, tenant, scenario, and permissions. The model should see the tool list available for the current turn after multiple filtering stages, rather than receiving every tool in the system. Exposing dozens of tools wastes context-window capacity and increases the probability of incorrect selection.

    1. public final class ToolRegistry {
    2. private final Map<String, Tool<?, ?>> tools = new ConcurrentHashMap<>();
    3. public void register(Tool<?, ?> tool) {
    4. // Validate name conflicts, version compatibility, and contract completeness
    5. }
    6. public List<ToolSpec> describe(ToolScope scope) {
    7. // Return tools visible after filtering by tenant, scenario, and permissions
    8. }
    9. }

    The registry should also provide health checks. A remote tool may become temporarily unavailable. The registry should track its health and either mark unavailable tools during description or remove them from the visible list, preventing the model from repeatedly selecting a failing tool.

    3.4 The Execution Pipeline

    Tool execution should not be a direct method call. It should be implemented as a pluggable pipeline:

    1. Parameter validation: Validate types and required fields against the input schema and fail early.
    2. Permission validation: Check whether the current subject has the required permissions. High-risk tools may trigger an approval flow.
    3. Quota validation: Apply tenant- and tool-level rate limits to prevent a single conversation from exhausting resources.
    4. Sandboxed execution: Run the tool in a restricted environment with limited filesystem, network, and process capabilities.
    5. Result processing: Truncate, paginate, or summarize oversized output to prevent context-window expansion.
    6. Auditing and metrics: Record parameter summaries, duration, and result status, and publish metrics.

    Each step should be an independent filter combined through a responsibility chain. This allows new governance policies to be added without modifying the executor itself, following the Open/Closed Principle.

    1. public final class ToolExecutor {
    2. private final List<ToolFilter> filters;
    3. public ToolResult execute(ToolCall call, ToolContext ctx) {
    4. return filters.stream()
    5. .reduce(ToolFilter::andThen)
    6. .map(chain -> chain.apply(call, ctx, this::doExecute))
    7. .orElseGet(() -> doExecute(call, ctx));
    8. }
    9. private ToolResult doExecute(ToolCall call, ToolContext ctx) {
    10. // Find the tool, deserialize parameters, invoke it, and serialize the result
    11. }
    12. }

    4. Two Extension Points: Standardized Protocols and Plugins

    4.1 Standardized Protocol Integration

    Remote tools can be integrated through a standardized protocol. The core operations are:

    1. Capability declaration
    2. Description retrieval
    3. Call forwarding
    4. Health checking

    A tool provider runs as an independent service and declares its supported tools and parameter structures. The framework periodically retrieves and caches these descriptions, then forwards calls according to the protocol.

    This approach is suitable for cross-language, cross-team, and independently deployed tools. Its cost is network uncertainty, so it requires timeouts, retries, circuit breakers, and fallback strategies. Protocol versions should also be negotiated explicitly to prevent provider upgrades from breaking client-side parsing.

    4.2 In-Process Plugins

    The plugin mechanism can use Java’s Service Provider Interface (SPI) together with independent class loaders. A plugin is delivered as an independent artifact and loaded during startup or at runtime. It can deeply reuse the framework’s domain objects and infrastructure capabilities.

    This approach offers low latency and tight integration, making it suitable for tools that need close cooperation with the main process. The trade-off is weaker isolation: a plugin defect may affect the host process. Class-loader isolation, dependency-version constraints, and fault-isolation compartments are therefore necessary.

    4.3 Trade-Offs

    Dimension Standardized protocol In-process plugin
    Deployment model Independent service Same-process artifact
    Language constraints None Primarily JVM-based
    Call latency Network overhead Method-call level
    Isolation Strong Depends on class-loader isolation
    Upgrade model Independent release Framework release or hot loading
    Suitable scenarios Cross-team, cross-language, strong isolation Deep integration, low latency

    In practice, both approaches can coexist. High-frequency core tools can use plugins, while long-tail and external capabilities can use protocols. The key is for both mechanisms to share the same tool contract and execution pipeline so that the orchestrator does not need to know how a tool is implemented.

    5. Applying DDD to Agent Systems

    5.1 Aggregate Design

    The Conversation aggregate uses a conversation identifier as its aggregate root and maintains the message sequence and context-window policy. Messages are appended rather than modified, supporting auditability and replay. Context compression is implemented as a domain service: it takes the complete message sequence as input and produces a reduced view.

    The Task aggregate manages the state machine for background tasks:

    • Submitted
    • Running
    • Succeeded
    • Failed
    • Cancelled

    State transitions must go through explicit methods. External code should not modify fields directly. Timeout and cancellation events are published and consumed by the scheduling layer.

    A Tool-call record is an independent entity containing the call identifier, tool name, parameter summary, result status, duration, and approval identifier. It should not be placed inside the Conversation aggregate, because that would make the aggregate unnecessarily large. Instead, it is associated through the call identifier.

    5.2 Domain Events

    Domain events are central to decoupling bounded contexts. Typical events include:

    • Tool call started
    • Tool call succeeded
    • Tool call failed
    • Task status changed
    • Approval requested
    • Approval completed
    • Quota exceeded

    After an event is published, the audit context can persist it, the metrics context can aggregate it, and the notification context can notify users. The publisher does not need to know which consumers exist, and consumers can evolve independently.

    Events should contain an idempotency key and an occurrence timestamp so consumers can deduplicate and order them.

    5.3 Anti-Corruption Layers

    Model output is usually a mixture of natural language and structured fragments. External protocol responses also use different formats. Neither should flow directly into the domain layer.

    An anti-corruption layer converts model output into domain commands, protocol responses into domain objects, and domain exceptions into error descriptions that the model can understand.

    This keeps the domain model pure: it knows its own language rather than the field names and conventions of external protocols.

    5.4 Application-Service Orchestration

    A complete conversation-processing flow is essentially an application service:

    1. public class AgentLoopAppService {
    2. public ConversationView handle(UserMessage message) {
    3. Conversation conversation = conversations.load(message.conversationId());
    4. Plan plan = planner.next(conversation, message);
    5. while (plan.hasToolCalls()) {
    6. List<ToolResult> results = toolExecutor.executeAll(
    7. plan.toolCalls(), contextOf(conversation));
    8. conversation = conversation.record(results);
    9. plan = planner.next(conversation);
    10. }
    11. conversations.save(conversation);
    12. return ConversationView.of(conversation);
    13. }
    14. }

    This example demonstrates several principles:

    • The conversation changes through aggregate methods rather than direct field updates.
    • Tool execution is delegated to a dedicated executor.
    • The loop has an explicit termination condition.
    • Persistence is performed consistently at the end of the use case.

    6. Cross-Cutting Concerns: Context, Concurrency, Security, and Observability

    6.1 Context and Memory

    Context-window capacity is limited. A practical strategy has three levels:

    • Keep recent messages in full.
    • Compress older messages into summaries.
    • Store long-term facts in memory storage and retrieve them when needed.

    Summary compression should preserve tool calls and key conclusions while removing verbose intermediate output. Retrieval should use a relevance threshold to prevent unrelated memories from consuming context-window space.

    6.2 Concurrency and Scheduling

    Tool calls can run in parallel only when they are read-only and explicitly declared parallelizable. Write and destructive operations must be serialized, with ordering preserved within the same conversation.

    Background tasks should use independent scheduling. After submission, the system returns a handle immediately, and results are obtained through queries or event notifications. Idempotency keys must remain available throughout the retry chain to prevent duplicate side effects.

    6.3 Security and Approval

    A secure execution strategy should include at least four layers:

    • Path allowlists to restrict file access
    • Command allowlists and argument validation to limit command-line capabilities
    • Network-domain allowlists to restrict outbound access
    • Sandboxed environments to limit processes and system calls

    High-risk operations should trigger human approval. If approval times out, the system should apply a predefined fallback policy, typically rejecting the operation.

    6.4 Observability and Cost

    Assign a trace identifier to every conversation and propagate it through request handling, orchestration, tool execution, and persistence.

    Structured logs should record key execution points. The metrics system should track call counts, success rates, latency distributions, and quota consumption. Cost data should be attributable by tenant, conversation, and tool so abnormal usage can be identified quickly.

    At the deployment level, artifacts and call records can be stored in object storage, structured logs can be sent to a logging service, and tool execution can run in containerized sandbox environments. These capabilities are available under corresponding service categories from cloud providers such as Baidu AI Cloud. Selection should be based on compliance requirements and budget.

    6.5 Testing Strategy

    Four categories of testing are particularly important:

    • Tool contract tests validate parameter checking, the error model, and result truncation.
    • Domain unit tests validate aggregate state transitions and domain rules.
    • Integration tests use replay: real calls are recorded as fixed inputs to verify the determinism of orchestration logic.
    • Fault-injection tests validate timeout, circuit-breaker, and fallback paths.

    Each category covers a different risk. None should be omitted.

    7. Implementation Roadmap: From a Minimal Loop to a Platform

    Stage 1: Minimal closed loop. Support one conversation, one tool, and in-memory storage. Implement the “reason, call, observe” loop. The goal is to validate whether the tool contract and execution pipeline are practical.

    Stage 2: Persistence and auditing. Persist conversations and tool-call records, then add structured logs and basic metrics. The goal is to make failures traceable and replayable.

    Stage 3: Dual extension points. Add remote protocol integration and in-process plugins, and verify that both tool types can coexist under the same contract. The goal is to allow new tools to be added without modifying the core codebase.

    Stage 4: Governance capabilities. Add permissions, approvals, quotas, sandboxing, and result processing. The goal is to make high-risk capabilities controllable.

    Stage 5: Platformization. Add multi-tenant isolation, marketplace-style tool registration, version rollout controls, and cost accounting. The goal is to turn the framework from a single project into shared infrastructure.

    Each stage should have clear acceptance criteria. Attempting to implement every module at once can cause complexity to grow beyond control.

    8. Conclusion

    Moving an Agent from a demo to production is not primarily about writing more sophisticated prompts. The core task is to establish an engineering structure that can support tool growth, evolving state, and security governance.

    Java’s strong type system and mature ecosystem are well suited to expressing clear contracts. DDD’s bounded contexts and aggregate design help control complexity. Together, they provide a stable foundation for an Agent framework.

    In practice, four principles are worth remembering:

    • Use unified contracts to control differences between tools.
    • Use dual extension points to support both local and remote capabilities.
    • Use aggregates and events to maintain state consistency.
    • Use an execution pipeline to apply governance throughout the lifecycle.

    When these four foundations are implemented carefully, the framework can continue to evolve without becoming increasingly fragile.