惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Forbes - Security
Forbes - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Palo Alto Networks Blog
Martin Fowler
Martin Fowler
T
Threatpost
D
Docker
S
Schneier on Security
M
MIT News - Artificial intelligence
G
Google Developers Blog
L
LINUX DO - 热门话题
J
Java Code Geeks
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
IT之家
IT之家
博客园 - Franky
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
V
Vulnerabilities – Threatpost
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
人人都是产品经理
人人都是产品经理
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
爱范儿
爱范儿
阮一峰的网络日志
阮一峰的网络日志
U
Unit 42
C
CERT Recently Published Vulnerability Notes
The GitHub Blog
The GitHub Blog
Simon Willison's Weblog
Simon Willison's Weblog
NISL@THU
NISL@THU
MongoDB | Blog
MongoDB | Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Heimdal Security Blog
Recorded Future
Recorded Future
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
P
Privacy International News Feed
P
Proofpoint News Feed
O
OpenAI News
B
Blog
腾讯CDC
F
Full Disclosure
Apple Machine Learning Research
Apple Machine Learning Research
T
Tor Project blog
H
Hacker News: Front Page
Project Zero
Project Zero
Hugging Face - Blog
Hugging Face - Blog
C
Cisco Blogs
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building an AI Chat Agent with MCP, Spring AI
Praveen Yadav · 2026-06-24 · via DEV Community

Model Context Protocol (MCP) is an open standard for connecting AI apps to tools and data sources. A useful way to think about it is as a USB-C port for AI: one standard interface that lets different models plug into different capabilities without custom glue code for every integration.

In this project, we combine MCP, Spring AI, and Google Gemini to build a chat app that can answer weather questions using real tools instead of hallucinating. The system has three parts:

  • MCP tool server - a Spring Boot service that exposes weather and geocoding tools
  • AI chat agent - a Spring Boot service that uses Spring AI + Gemini and calls MCP tools when needed
  • React chat UI - a lightweight frontend for sending messages and rendering replies

The result is a small but realistic architecture you can extend into a production assistant.

Architecture

User (Browser:3000)
    | POST /api/chat
    v
AI Agent (Spring:7171) -- MCP / Streamable HTTP --> MCP Server (Spring:7170)
    |                                               |
    | Google Gemini                                 | Bright Sky API (weather)
    |                                               | OpenStreetMap Nominatim (geocoding)
    v                                               v
Chat response                                    Tool execution

The full source code is available on GitHub.


1. The MCP Tool Server

The tool server is a Spring Boot application that exposes MCP tools through Spring AI's annotation scanner. It runs on port 7170 and uses Streamable HTTP for transport.

Dependencies

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-server-webmvc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Defining tools

With Spring AI, a tool is just a Spring bean method annotated with @McpTool:

@Component
public class WeatherTool {

    private final WeatherToolService weatherToolService;

    public WeatherTool(WeatherToolService weatherToolService) {
        this.weatherToolService = weatherToolService;
    }

    @McpTool(name = "get_current_weather",
             description = "Get current weather by dwd_station_id or by lat/lon")
    public Map<String, Object> getCurrentWeather(
            @McpToolParam(description = "DWD station ID", required = false)
            String dwd_station_id,
            @McpToolParam(description = "Latitude", required = false) Double lat,
            @McpToolParam(description = "Longitude", required = false) Double lon
    ) {
        return weatherToolService.getWeather(dwd_station_id, lat, lon);
    }
}

Spring turns that method into an MCP tool definition and publishes the parameter metadata as part of the schema. That means the model can discover the tool, understand its inputs, and decide when to call it.

The project also includes a geocoding tool that resolves city names to coordinates:

@McpTool(name = "geocode_city",
         description = "Convert a city name to latitude and longitude using OpenStreetMap Nominatim")
public Map<String, Object> geocodeCity(
        @McpToolParam(description = "City name (e.g., 'Berlin', 'New York')", required = true)
        String cityName
) { ... }

The service layer

The tools delegate the real work to services that handle validation, caching, and external API calls:

@Service
public class WeatherToolService {

    public Map<String, Object> getWeather(String dwdStationId, Double lat, Double lon) {
        // Validate the request
        // Check the cache
        // Call Bright Sky if needed
        // Return a structured response
    }
}

The key design choices are straightforward:

  • Separate TTL caches for station-id and coordinate lookups
  • Structured responses with success, error_code, and error_message
  • Cache metadata in each response so you can see whether the result came from cache or upstream

Server configuration

server:
  port: 7170

spring:
  ai:
    mcp:
      server:
        name: spring-sample-mcp-server
        version: 1.0.0
        protocol: STREAMABLE
        type: SYNC
        annotation-scanner:
          enabled: true

mcp:
  security:
    api-key: ${MCP_API_KEY:}

The STREAMABLE protocol gives the agent a lightweight MCP transport, and the shared API key keeps the demo simple without adding full auth infrastructure.


2. Security for the Demo

The MCP server and agent share an MCP_API_KEY. The agent adds it automatically as an X-API-Key header, and the server validates it on inbound MCP requests.

That is enough for local development and a sample project. For anything public-facing, move to Spring Security, OAuth2 or JWT, rate limiting, and a gateway in front of the MCP endpoint.


3. The AI Chat Agent

The agent is responsible for deciding when to use tools, calling Gemini, and keeping the conversation stateful.

Dependencies

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-google-genai</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

MCP client configuration

The agent injects the shared API key through a custom HTTP request customizer:

@Configuration
public class AgentConfiguration {

    @Bean
    McpClientCustomizer<HttpClientStreamableHttpTransport.Builder>
    streamableHttpTransportCustomizer(AgentProperties properties) {
        McpSyncHttpClientRequestCustomizer requestCustomizer =
                (builder, method, uri, body, context) -> {
                    if (StringUtils.hasText(properties.getMcpApiKey())) {
                        builder.header("X-API-Key", properties.getMcpApiKey());
                    }
                };
        return (name, builder) -> builder.httpRequestCustomizer(requestCustomizer);
    }
}

Core chat flow

The agent keeps a small in-memory conversation history, checks whether the user message looks like a tool request, and then routes the prompt through either a plain Gemini client or a tool-enabled client.

public String reply(String sessionId, String userMessage) {
    List<ConversationTurn> history = memoryStore.history(sessionId);
    String prompt = buildPrompt(history, userMessage);
    boolean toolRequest = shouldUseTools(userMessage);
    ChatClient client = toolRequest ? toolEnabledClient() : plainChatClient;
    String answer = invokeModel(client, prompt);
    memoryStore.appendTurn(sessionId, userMessage, answer);
    return answer;
}

The lazy initialization is deliberate: the agent can start even if the MCP server is down, and it only initializes MCP clients when a tool request actually arrives.

The tool trigger is intentionally simple:

private static boolean shouldUseTools(String userMessage) {
    String normalized = userMessage.toLowerCase(Locale.ROOT);
    for (String keyword : TOOL_KEYWORDS) {
        if (normalized.contains(keyword)) {
            return true;
        }
    }
    return false;
}

That heuristic is enough for a demo and easy to explain. In a larger system, you could replace it with a router model or intent classifier.

Virtual threads and timeout handling

The model call runs on a virtual thread with a configurable timeout so the request does not hang forever if Gemini is slow or unreachable:

private String invokeModel(ChatClient client, String prompt) {
    var executor = Executors.newVirtualThreadPerTaskExecutor();
    try {
        var future = executor.submit(() ->
                client.prompt().user(prompt).call().content());
        return future.get(timeoutSeconds, TimeUnit.SECONDS);
    } catch (TimeoutException ex) {
        throw new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, ...);
    } finally {
        executor.shutdownNow();
    }
}

Session memory

Conversation history lives in an in-memory LRU store with a small per-session turn window. That keeps follow-up questions like "What about tomorrow?" grounded in the earlier exchange without introducing a database too early.

The agent configuration sets the model to gemini-3.5-flash, the memory limit to 20 turns per session, and the session cap to 500.


4. The React Chat UI

The frontend is a Vite app with a simple chat window, minimal state, and no component library.

const [messages, setMessages] = useState([]);
const [loading, setLoading] = useState(false);

const sendMessage = async (text) => {
    setMessages(prev => [...prev, { role: 'user', content: text }]);
    setLoading(true);
    const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionId, message: text })
    });
    const data = await response.json();
    setMessages(prev => [...prev, {
        role: 'assistant',
        content: data.reply || 'No response'
    }]);
    setLoading(false);
};

The Vite dev server proxies /api/* to the agent:

proxy: {
  '/api': {
    target: 'http://localhost:7171',
    changeOrigin: true,
    rewrite: (path) => path.replace(/^\/api/, '')
  }
}

The UI is intentionally plain: a purple gradient, responsive layout, and a smooth message list are enough to make the app feel complete without distracting from the architecture.


5. Putting It All Together

Running the application

  1. Set the environment variables:
export GEMINI_API_KEY=your_gemini_api_key
export MCP_API_KEY=a_shared_secret

  1. Start the MCP server:
cd mcp-server-spring
mvn spring-boot:run

  1. Start the agent:
cd mcp-spring-agent
mvn spring-boot:run

  1. Start the UI:
cd mcp-ui
npm install
npm run dev

What happens when you ask a question

If the user asks, "What's the weather in Berlin?" the flow looks like this:

  1. The agent sees the word "weather" and switches to tool-enabled mode
  2. Gemini calls geocode_city("Berlin") to get coordinates
  3. The agent calls get_current_weather(lat=52.52, lon=13.41)
  4. Gemini turns the raw data into a readable response
  5. The UI renders the answer

6. Why This Architecture Works

MCP separates the model from the tools. The agent knows what tools exist and how to call them, but not how those tools are implemented. That makes the system easier to evolve.

The same server can serve different models. Gemini is just the model in this demo. The MCP server itself can work with any compatible client.

Lazy initialization keeps the app resilient. The agent can boot even if the MCP server is temporarily unavailable, and tool support only activates when it is actually needed.


7. What's Next

This sample is a solid starting point. Natural next steps include:

  • Docker Compose - run all services together
  • PostgreSQL persistence - durable chat history and richer memory
  • OAuth2 - authenticated multi-user access
  • WebSocket streaming - token-by-token responses
  • Kubernetes - scale the agent and tool server independently

Resources


Have you built anything with MCP and Spring AI? I'd love to hear how you approached it.