Spring AI Agent Utils

repository·main·Indexed 19 days ago

https://github.com/spring-ai-community/spring-ai-agent-utils

A library that reimplements Claude Code-inspired tools and agent skills for the Spring AI ecosystem. It provides Java developers with capabilities for file operations, shell execution, web access, and multi-agent orchestration, including specialized tools like AskUserQuestionTool, FileSystemTools, ShellTools, and integration with Model Context Protocol (MCP) servers.

Tokens
94.5K
Snippets
227
Records
336
Agent score
65%

What's inside Spring AI Agent Utils

  1. Overview of Agentic Utils

    main

    The library provides several categories of tools to enable sophisticated agentic workflows:

    Core Tools

    • AgentEnvironment: Provides runtime environment info and git status to system prompts.
    • FileSystemTools: Read, write, and edit files.
    • ShellTools: Execute shell commands with timeout and background process management.
    • GrepTool: Java-based regex code search.
    • GlobTool: File pattern matching using glob syntax.
    • SmartWebFetchTool: AI-powered web content summarization with caching.
    • BraveWebSearchTool: Web search with domain filtering.

    User Feedback

    • AskUserQuestionTool: Allows agents to ask users clarifying questions with multiple-choice options.

    Agent Skills

    • SkillsTool: Reusable, composable knowledge modules defined in Markdown with YAML front-matter.

    Long-term Memory

    • AutoMemoryTools: Persistent, file-based memory (user, feedback, project, reference) using a MEMORY.md index. Requires a specific system prompt.
    • AutoMemoryToolsAdvisor: A ChatClient advisor that automates AutoMemoryTools and its system prompt registration.

    Task Orchestration & Multi-Agent

    • TodoWriteTool: Structured task management with state tracking.
    • TaskTools: Sub-agent system for delegating tasks to specialized agents with multi-model routing.
  2. Overview of Agentic Utils and Tools

    main

    Spring AI Agent Utils provides a suite of tools designed to implement agentic behavior, inspired by Claude Code. These tools are categorized into several functional groups:

    Core Tools

    • AgentEnvironment: Provides runtime environment info and git repository status to system prompts.
    • FileSystemTools: Enables reading, writing, and editing files.
    • ShellTools: Executes shell commands with timeout, background process, and regex filtering support.
    • GrepTool: Java-based grep for code search using regex and glob filtering.
    • GlobTool: Fast file pattern matching using glob syntax.
    • SmartWebFetchTool: AI-powered web content summarization with caching.
    • BraveWebSearchTool: Web search capabilities with domain filtering.

    User Feedback

    • AskUserQuestionTool: Allows the agent to ask users clarifying questions (including multiple-choice) during execution.

    Agent Skills

    • SkillsTool: Extends agent capabilities via reusable, composable knowledge modules defined in Markdown with YAML front-matter.

    Task Orchestration & Multi-Agent

    • TodoWriteTool: Manages structured tasks with state tracking.
    • TaskTools: A hierarchical system for delegating complex tasks to specialized sub-agents with dedicated context windows.
  3. Use the ai-tutor skill for technical explanations

    main

    The ai-tutor skill is designed for agents that need to explain, break down, or help users understand complex technical concepts (such as AI, ML, or other technical topics). It transforms complex ideas into accessible explanations using narrative storytelling frameworks, plain English, and concrete examples.

    When to use:

    • When a user asks to explain a concept.
    • When a user needs help understanding technical documentation or workflows.
    • When a user provides a YouTube video link and needs a breakdown of its content.
  4. Module structure of Task Tools

    main

    The subagent system is organized into three distinct modules:

    • spring-ai-agent-utils-common: Contains the Core SPI (Service Provider Interface) including SubagentDefinition, SubagentResolver, SubagentExecutor, SubagentType, SubagentReference, and TaskCall.
    • spring-ai-agent-utils: The main implementation containing TaskTool, TaskOutputTool, ClaudeSubagentType, ClaudeSubagentExecutor, and ClaudeSubagentResolver.
    • spring-ai-agent-utils-a2a: An optional dependency providing A2ASubagentDefinition, A2ASubagentResolver, and A2ASubagentExecutor for the A2A protocol.
  5. Explore available agent examples

    main

    The examples/ directory contains several specialized demonstrations of the spring-ai-agent-utils library:

    • Code Agent Demo: An interactive CLI coding assistant (inspired by Claude Code).
    • Ask User Question Demo: Uses AskUserQuestionTool for structured, interactive communication (including multiple-choice options).
    • Sub-Agent Demo: Implements a hierarchical system using Markdown-defined local sub-agents and the TaskTool dispatcher pattern.
    • Sub-Agent A2A Demo: Extends sub-agents with the A2A (Agent-to-Agent) protocol for delegating tasks to remote agents via HTTP.
    • Skills Demo: Demonstrates the SkillsTool system and how to develop custom skills.
    • Todo Demo: Uses TodoWriteTool for structured task management, allowing LLMs to create and track task lists with real-time progress updates via Spring application events.
  6. Understand the TodoWriteTool task structure

    main

    The TodoWriteTool manages a list of tasks. Each task is defined by three specific fields that represent the lifecycle of an operation:

    FieldDescriptionExample
    contentThe imperative description of what needs to be done"Run tests"
    activeFormThe continuous description of what is currently happening"Running tests"
    statusThe current state of the task. Valid values are: pending, in_progress, completed

    Critical Constraint: The tool enforces a rule where exactly ONE task can have the status in_progress at any given time.

  7. How the Main Agent operates

    main

    The Main Agent is an interactive CLI tool designed for software engineering tasks such as bug fixing, refactoring, and code explanation. It operates under a strict set of behavioral principles:

    • Defensive Security Only: The agent will refuse to assist with malicious activities, credential harvesting (e.g., SSH keys, cookies), or bulk crawling. It only supports defensive security tasks like vulnerability analysis and detection rules.
    • Professional Objectivity: The agent prioritizes technical accuracy and facts over user validation. It is designed to provide objective guidance and may disagree with user beliefs if technical evidence suggests otherwise.
    • Task Management via TodoWrite: The agent uses a TodoWrite tool to plan complex tasks, break them into smaller steps, and track progress. It marks tasks as in_progress and completed to provide visibility.
    • Communication Style: Responses are intended for a command-line interface (CLI). They are short, concise, and use GitHub-flavored markdown. Emojis are avoided unless explicitly requested.
  8. How AutoMemoryTools works

    main

    The AutoMemoryTools system manages long-term memory through a two-step automated process triggered by the agent via tool calls:

    1. MemoryCreate: The agent writes a typed .md file containing YAML frontmatter (defining name, description, and type) and the memory content.
    2. MemoryInsert: The agent appends a pointer to these new memories in a central MEMORY.md index file.

    Retrieval Lifecycle: On subsequent sessions, the agent calls MemoryView("MEMORY.md", null) to read the index, then selectively calls MemoryView("filename.md", null) for specific entries that are relevant to the current user prompt.

    Supported Memory Types

    TypePurposeExample
    userBackground, goals, or preferencesname, role, communication style
    feedbackCorrections or behavioral confirmations"stop summarizing at the end"
    projectDecisions, deadlines, or constraintsmigration targets, freeze dates
    referencePointers to external systemsLinear boards, Grafana dashboards
  9. How A2A subagents work in Spring AI Agent Utils

    main

    The A2A (Agent-to-Agent) module allows an AI agent to delegate tasks to remote agents using the A2A protocol. It integrates with the existing TaskTool SPI, meaning remote A2A agents are treated similarly to local Claude subagents.

    Workflow:

    1. Discovery: The A2ASubagentResolver fetches an AgentCard from the remote agent's well-known endpoint (<uri>/.well-known/agent-card.json).
    2. Definition: The resolver creates an A2ASubagentDefinition (wrapping the AgentCard) which describes the remote agent's capabilities.
    3. Execution: The A2ASubagentExecutor sends a message via JSON-RPC transport, waits up to 60 seconds for completion, and extracts text from the response artifacts.
    TaskTool
      │
      ├── SubagentReference("http://host:port/path", "A2A")
      │         │
      │         ▼
      │   A2ASubagentResolver
      │     ── fetches /.well-known/agent-card.json
      │     ── returns A2ASubagentDefinition (wraps AgentCard)
      │
      └── A2ASubagentExecutor
            ── sends message via JSON-RPC transport
            ── waits for task completion (60s timeout)
            ── extracts text from response artifacts
  10. Filter search results by domain

    main

    You can filter results using two different methods: Client-side filtering (via tool parameters) or Server-side filtering (via search operators).

    Client-Side Filtering (Using Tool Parameters)

    Filtering is applied after the results are fetched. Note: These results still count against your API quota.

    • allowedDomains: A list of domains to include. Matches subdomains automatically (e.g., spring.io matches docs.spring.io).
    • blockedDomains: A list of domains to exclude.
    // Only include results from spring.io
    searchTool.webSearch("query", List.of("spring.io"), null);
    
    // Exclude specific domains
    searchTool.webSearch("query", null, List.of("example.com"));

    To save API quota and improve speed, use Brave's native search operators directly in the query string. This ensures results are filtered by Brave before they reach your application.

    • site:domain.com to include a domain.
    • -site:domain.com to exclude a domain.
    • (site:a.com OR site:b.com) for multiple domains.
    // Efficient: Server-side filtering
    String results = searchTool.webSearch("Spring AI site:spring.io", null, null);
    
    // Efficient: Exclude a domain
    String results2 = searchTool.webSearch("Java tutorial -site:example.com", null, null);
  11. Memory Types and Usage Guidelines

    main

    The system categorizes information into four discrete types. Choosing the correct type ensures the agent uses the information effectively:

    • user: Information about the user's role, goals, responsibilities, and knowledge. Use this to tailor expertise levels and perspectives (e.g., knowing a user is a Go expert but new to React).
    • feedback: Guidance on what to avoid or what to keep doing. Include the Why (the reason) and How to apply (when the guidance kicks in) to avoid blind rule-following. Record both successes and failures.
    • project: Context about ongoing work, goals, or constraints not found in code/git (e.g., merge freezes, compliance requirements). Important: Always convert relative dates (e.g., "Thursday") to absolute dates (e.g., "2026-03-05").
    • reference: Pointers to external systems like Linear projects, Slack channels, or Grafana dashboards.