<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vikalp on Medium]]></title>
        <description><![CDATA[Stories by Vikalp on Medium]]></description>
        <link>https://medium.com/@vikalp481?source=rss-eefda2537786------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2mwFQG4ubvn0vsiC</url>
            <title>Stories by Vikalp on Medium</title>
            <link>https://medium.com/@vikalp481?source=rss-eefda2537786------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:27:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikalp481/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Production-Ready RAG System with Spring AI and Local LLMs]]></title>
            <link>https://medium.com/@vikalp481/building-a-production-ready-rag-system-with-spring-ai-and-local-llms-4b4a98dbf6f1?source=rss-eefda2537786------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b4a98dbf6f1</guid>
            <category><![CDATA[pgvector]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[ollama]]></category>
            <dc:creator><![CDATA[Vikalp]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 20:45:16 GMT</pubDate>
            <atom:updated>2025-12-19T20:45:16.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Another RAG Tutorial?</h3><p>You’ve probably seen dozens of RAG (Retrieval-Augmented Generation) tutorials using Python, LangChain, and OpenAI. But what if you’re working in a Java ecosystem? What if you need enterprise-grade features like dependency injection, reactive programming, and robust error handling? And what if you want to keep your data completely private by running everything locally?</p><p>That’s where Spring AI comes in.</p><p>In this article, I’ll show you how to build a production-ready RAG system that can answer questions about your documents using Spring Boot, Ollama, and pgvector. No external API keys required, no data leaving your infrastructure.</p><h3>What is RAG and Why Should You Care?</h3><p>RAG is a technique that combines the power of large language models with your own data. Instead of hoping the LLM has the information you need (or worse, making it up), RAG:</p><ol><li><strong>Retrieves</strong> relevant information from your document database</li><li><strong>Augments</strong> the prompt with that context</li><li><strong>Generates</strong> an answer based on actual facts from your documents</li></ol><p>Think of it as giving your LLM a search engine and a fact-checker before it answers.</p><h3>The Architecture: Simple but Powerful</h3><p>Our system has four main components:</p><p><strong>PostgreSQL + pgvector</strong>: Stores document embeddings for lightning-fast similarity search <strong>Ollama</strong>: Runs LLMs locally (we’ll use llama3.2 for chat and nomic-embed-text for embeddings) <strong>Spring AI</strong>: Orchestrates everything with clean, enterprise-ready code <strong>Spring WebFlux</strong>: Provides reactive, non-blocking APIs</p><p>The beauty of this setup? Everything runs on your machine. No API costs, no data privacy concerns, no vendor lock-in.</p><h3>Let’s Build It</h3><h3>Step 1: Setting Up the Foundation</h3><p>First, we need a vector database. While many tutorials use ChromaDB or Pinecone, I prefer PostgreSQL with pgvector for production systems. Why? Because you probably already have PostgreSQL expertise in your organization, and pgvector gives you ACID transactions, backup strategies, and monitoring tools you already know.</p><p>Create a docker-compose.yml:</p><p>yaml</p><pre>version: &#39;3.8&#39;</pre><pre>services:<br>  postgres:<br>    image: pgvector/pgvector:pg16<br>    environment:<br>      POSTGRES_DB: vectordb<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - pgvector-data:/var/lib/postgresql/data</pre><p>Start it with docker-compose up -d and you&#39;ve got a vector-capable database ready to go.</p><h3>Step 2: Spring Boot Project Structure</h3><p>The Maven setup is straightforward. The key dependencies are:</p><p>xml</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-starter-model-ollama&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-starter-vector-store-pgvector&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-pdf-document-reader&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Spring AI abstracts away the complexity of working with embeddings and vector stores, giving you clean interfaces to work with.</p><h3>Step 3: The Heart of RAG — Document Ingestion</h3><p>This is where the magic starts. We need to:</p><ul><li>Read PDFs</li><li>Split them into manageable chunks</li><li>Generate embeddings</li><li>Store them in our vector database</li></ul><p>Here’s the core ingestion logic:</p><p>java</p><pre>public String ingestDocuments() {<br>    // Load PDFs from classpath<br>    Resource[] resources = resolver.getResources(&quot;classpath:/pdfs/*.pdf&quot;);<br>    <br>    List&lt;Document&gt; allDocuments = new ArrayList&lt;&gt;();<br>    <br>    // Read each PDF<br>    for (Resource resource : resources) {<br>        PagePdfDocumentReader pdfReader = new PagePdfDocumentReader(resource);<br>        List&lt;Document&gt; documents = pdfReader.get();<br>        <br>        // Add metadata for traceability<br>        documents.forEach(doc -&gt; <br>            doc.getMetadata().put(&quot;source&quot;, resource.getFilename())<br>        );<br>        <br>        allDocuments.addAll(documents);<br>    }<br>    <br>    // Split into chunks (500 tokens, 100 token overlap)<br>    TextSplitter textSplitter = new TokenTextSplitter(500, 100, 5, 10000, true);<br>    List&lt;Document&gt; chunks = textSplitter.apply(allDocuments);<br>    <br>    // Store in vector database<br>    vectorStore.add(chunks);<br>    <br>    return &quot;Ingested &quot; + chunks.size() + &quot; document chunks&quot;;<br>}</pre><p>Why 500 tokens with 100 token overlap? This ensures each chunk has enough context while maintaining some continuity between chunks. It’s a balance I’ve found works well in practice.</p><h3>Step 4: Implementing the RAG Query Flow</h3><p>Now for the exciting part — answering questions! The RAG flow has three steps:</p><p><strong>Retrieve</strong>: Find the most relevant document chunks <strong>Augment</strong>: Build a prompt with the retrieved context <strong>Generate</strong>: Let the LLM answer based on that context</p><p>java</p><pre>public String chat(String question) {<br>    // Step 1: Retrieve relevant documents<br>    List&lt;Document&gt; relevantDocs = vectorStore.similaritySearch(<br>        SearchRequest.builder()<br>            .query(question)<br>            .topK(5)<br>            .build()<br>    );<br>    <br>    if (relevantDocs.isEmpty()) {<br>        return &quot;No relevant information found in the knowledge base.&quot;;<br>    }<br>    <br>    // Step 2: Augment - Prepare context<br>    String context = relevantDocs.stream()<br>        .map(Document::getFormattedContent)<br>        .collect(Collectors.joining(&quot;\n\n&quot;));<br>    <br>    // Step 3: Generate - Create prompt and get response<br>    String promptTemplate = &quot;&quot;&quot;<br>        You are a helpful assistant. Answer the question based on the following context.<br>        If you cannot find the answer in the context, say so.<br>        <br>        Context:<br>        {context}<br>        <br>        Question: {question}<br>        <br>        Answer:<br>        &quot;&quot;&quot;;<br>    <br>    PromptTemplate template = new PromptTemplate(promptTemplate);<br>    Prompt prompt = template.create(Map.of(<br>        &quot;context&quot;, context,<br>        &quot;question&quot;, question<br>    ));<br>    <br>    return chatClient.prompt(prompt).call().content();<br>}</pre><p>The beauty of this approach? The LLM only sees relevant context, reducing hallucinations and improving answer quality.</p><h3>Step 5: Reactive REST API</h3><p>Since we’re using Spring WebFlux, we can handle requests efficiently without blocking:</p><p>java</p><pre>@PostMapping(&quot;/chat&quot;)<br>public Mono&lt;ResponseEntity&lt;Map&lt;String, String&gt;&gt;&gt; chat(<br>        @RequestBody Map&lt;String, String&gt; request) {<br>    <br>    String question = request.get(&quot;question&quot;);<br>    <br>    return Mono.fromCallable(() -&gt; ragService.chat(question))<br>        .subscribeOn(Schedulers.boundedElastic())<br>        .map(response -&gt; ResponseEntity.ok(Map.of(<br>            &quot;question&quot;, question,<br>            &quot;answer&quot;, response<br>        )));<br>}</pre><p>This offloads the blocking operations (database queries, LLM calls) to a separate thread pool, keeping your API responsive.</p><h3>Configuration: The Devil’s in the Details</h3><p>Getting Ollama configured correctly is crucial:</p><p>yaml</p><pre>spring:<br>  ai:<br>    ollama:<br>      base-url: http://localhost:11434<br>      connect-timeout: 60s<br>      read-timeout: 300s  # Generous timeout for model loading<br>      <br>      chat:<br>        model: llama3.2<br>        options:<br>          temperature: 0.7<br>          <br>      embedding:<br>        model: nomic-embed-text<br>    <br>    vectorstore:<br>      pgvector:<br>        index-type: HNSW<br>        distance-type: COSINE_DISTANCE<br>        dimensions: 768<br>        initialize-schema: true</pre><p>The nomic-embed-text model produces 768-dimensional embeddings, which is why we configure pgvector with dimensions: 768. The HNSW index type provides excellent performance for approximate nearest neighbor search.</p><h3>Testing It Out</h3><p>First, install Ollama and pull the models:</p><p>bash</p><pre>ollama pull llama3.2<br>ollama pull nomic-embed-text</pre><p>Start your application and ingest some documents:</p><p>bash</p><pre>curl -X POST http://localhost:8080/api/ingest</pre><p>Now ask a question:</p><p>bash</p><pre>curl -X POST http://localhost:8080/api/chat \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;question&quot;: &quot;What are the main topics covered in the documents?&quot;}&#39;</pre><h3>What Makes This Production-Ready?</h3><p><strong>Local and Private</strong>: All data stays on your infrastructure <strong>Scalable</strong>: Reactive programming model handles concurrent requests efficiently <strong>Observable</strong>: Easy to add metrics, logging, and monitoring <strong>Maintainable</strong>: Clean separation of concerns with Spring’s dependency injection <strong>Reliable</strong>: PostgreSQL’s ACID guarantees and backup strategies <strong>Cost-Effective</strong>: No API usage fees, just compute costs</p><h3>Common Pitfalls and Solutions</h3><h3>Chunk Size Matters</h3><p>Too small chunks lack context. Too large chunks dilute relevance. Start with 500 tokens and adjust based on your documents.</p><h3>Temperature Tuning</h3><p>For factual Q&amp;A, keep temperature around 0.7. Lower (0.3–0.5) for more deterministic answers, higher (0.8–1.0) for creative responses.</p><h3>Similarity Search Top-K</h3><p>Retrieving too few documents misses context. Too many adds noise. I’ve found 5 works well as a starting point.</p><h3>Metadata is Your Friend</h3><p>Always add source information to your documents. It helps with debugging and allows you to show users where information came from.</p><h3>Real-World Applications</h3><p>This architecture works great for:</p><ul><li><strong>Internal knowledge bases</strong>: HR policies, technical documentation, procedures</li><li><strong>Customer support</strong>: Product manuals, FAQ databases, troubleshooting guides</li><li><strong>Legal and compliance</strong>: Contract analysis, regulation lookup, policy Q&amp;A</li><li><strong>Research</strong>: Paper summarization, citation lookup, literature review</li></ul><h3>Next Steps</h3><p>Want to take this further? Consider:</p><ul><li>Adding authentication and rate limiting</li><li>Implementing conversation history</li><li>Adding a frontend with streaming responses</li><li>Creating domain-specific embeddings through fine-tuning</li><li>Implementing hybrid search (combining semantic and keyword search)</li><li>Adding re-ranking for better result quality</li></ul><h3>Conclusion</h3><p>Building a RAG system doesn’t have to mean leaving the Java ecosystem or relying on external APIs. Spring AI brings enterprise-grade AI capabilities to Spring developers with familiar patterns and abstractions.</p><p>The combination of Spring Boot’s robustness, Ollama’s local LLMs, and pgvector’s efficiency gives you a production-ready system that’s private, scalable, and maintainable.</p><p>The full code is available on GitHub <a href="https://github.com/Viktechenthu/spring-rag-system">https://github.com/Viktechenthu/spring-rag-system</a>. Give it a try and let me know what you build with it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b4a98dbf6f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Spring Boot Features with GitHub Copilot: A Pattern-Based Approach]]></title>
            <link>https://medium.com/@vikalp481/building-spring-boot-features-with-github-copilot-a-pattern-based-approach-90b278c30c68?source=rss-eefda2537786------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b278c30c68</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Vikalp]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 17:00:30 GMT</pubDate>
            <atom:updated>2025-11-14T17:12:32.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QxFe4P3UtK9QBcy_3LKvQ.png" /></figure><p><a href="https://youtu.be/Orqt0kGi6JE">Video</a></p><h3>How I Added Complete CRUD Functionality with a Single Prompt</h3><p>As developers, we often find ourselves repeating similar patterns across our codebase. Entity creation, repository setup, service layer implementation, REST controllers — it’s all necessary work, but it can feel repetitive. What if we could teach our AI assistant to understand our project’s patterns and generate consistent, high-quality code?</p><p>In this article, I’ll show you how I used GitHub Copilot with custom instructions to add a complete appointment scheduling feature to my Spring Boot healthcare system — with just one prompt.</p><h3>The Challenge: Maintaining Consistency Across Features</h3><p>I was building a Patient Care System with Spring Boot that already had three main features:</p><ul><li><strong>Patients</strong>: Core entity with basic CRUD operations</li><li><strong>Progress Notes</strong>: Clinical notes linked to patients</li><li><strong>Care Plans</strong>: Treatment plans for patients</li></ul><p>Each feature followed a specific pattern:</p><ol><li>JPA Entity with Lombok annotations</li><li>Spring Data JPA Repository with custom queries</li><li>Service layer with transactional business logic</li><li>REST Controller with standardized endpoints</li><li>MCP (Model Context Protocol) tools for AI integration</li><li>Sample data initialization</li></ol><p>The problem? Manually implementing this pattern for each new feature was time-consuming and error-prone. Different developers might implement things slightly differently, leading to inconsistency.</p><h3>The Solution: Custom Copilot Instructions</h3><p>Rather than treating GitHub Copilot as a generic code assistant, I created a comprehensive copilot-instructions.md file that serves as the &quot;source of truth&quot; for my project&#39;s architecture and patterns.</p><h3>What’s in copilot-instructions.md?</h3><p>Here’s what my instructions file contains:</p><p><strong>1. Project Overview</strong></p><ul><li>Technology stack (Spring Boot 3.2.0, Java 17, H2 Database)</li><li>High-level architecture description</li><li>Key dependencies</li></ul><p><strong>2. Package Structure Standards</strong></p><pre>com.healthcare.patientcare/<br>├── entity/          # JPA entities<br>├── repository/      # Spring Data repositories<br>├── service/         # Business logic<br>├── controller/      # REST endpoints<br>├── mcp/            # MCP integration<br>└── config/         # Configuration</pre><p><strong>3. Naming Conventions</strong></p><ul><li>Entities: Singular noun (Patient, Appointment)</li><li>Tables: Plural lowercase (patients, appointments)</li><li>Services: {Entity}Service</li><li>Controllers: {Entity}Controller</li><li>Repositories: {Entity}Repository</li></ul><p><strong>4. Code Templates and Patterns</strong></p><p>For example, here’s the entity pattern:</p><pre>@Entity<br>@Table(name = &quot;table_name&quot;)<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class EntityName {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    <br>    // Entity-specific fields<br>    <br>    // Relationships with @JsonIgnore to prevent circular refs<br>}</pre><p><strong>5. Relationship Patterns</strong></p><ul><li>How to handle @ManyToOne relationships</li><li>Where to place @JsonIgnore annotations</li><li>Proper cascade configurations</li></ul><p><strong>6. MCP Tool Integration</strong></p><ul><li>Custom @Tool annotation usage</li><li>Parameter descriptions with @ToolParam</li><li>Error handling patterns</li></ul><p><strong>7. Critical Rules</strong></p><ul><li>Always use @JsonIgnore on child entity references</li><li>Initialize collections in entities</li><li>Throw RuntimeException with descriptive messages</li><li>Keep controllers thin, business logic in services</li></ul><h3>The Magic Prompt</h3><p>With my instructions file in place, I gave GitHub Copilot this single prompt:</p><pre>@workspace I need to add a new feature for scheduling appointments. <br>Create the following components following the conventions in <br>copilot-instructions.md:</pre><pre>1. Appointment entity with fields: appointmentDate (LocalDateTime), <br>   reason (String), status (String), provider (String), and a <br>   ManyToOne relationship to Patient<br>2. AppointmentRepository with custom methods to find by patientId <br>   and by date range<br>3. AppointmentService with methods for CRUD operations and querying<br>4. AppointmentController with REST endpoints at /api/appointments<br>5. Add MCP tools in MCPToolService: schedule_appointment, <br>   get_appointments, cancel_appointment<br>6. Update Patient entity to add OneToMany relationship to Appointments<br>7. Add sample appointment data in DataInitializer</pre><pre>Generate all files following the exact patterns used in the existing <br>Patient, ProgressNote, and CarePlan features.</pre><h3>What GitHub Copilot Generated</h3><p>Within seconds, Copilot generated <strong>seven complete files</strong> that perfectly matched my project’s patterns:</p><h3>1. Appointment Entity</h3><pre>@Entity<br>@Table(name = &quot;appointments&quot;)<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class Appointment {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;</pre><pre>    private LocalDateTime appointmentDate;<br>    <br>    @Column(length = 2000)<br>    private String reason;<br>    <br>    private String status;<br>    private String provider;</pre><pre>    @ManyToOne(fetch = FetchType.LAZY)<br>    @JoinColumn(name = &quot;patient_id&quot;, nullable = false)<br>    @JsonIgnore  // Prevents circular JSON serialization<br>    private Patient patient;<br>}</pre><p><strong>Notice how it:</strong></p><ul><li>Used correct Lombok annotations</li><li>Added @Column(length = 2000) for text fields</li><li>Applied @JsonIgnore on the parent relationship</li><li>Used FetchType.LAZY for performance</li></ul><h3>2. AppointmentRepository</h3><pre>@Repository<br>public interface AppointmentRepository <br>    extends JpaRepository&lt;Appointment, Long&gt; {<br>    <br>    List&lt;Appointment&gt; findByPatientId(Long patientId);<br>    <br>    List&lt;Appointment&gt; findByAppointmentDateBetween(<br>        LocalDateTime start, <br>        LocalDateTime end<br>    );<br>}</pre><p>Custom query methods following Spring Data JPA conventions — no @Query needed!</p><h3>3. AppointmentService</h3><pre>@Service<br>@Transactional<br>public class AppointmentService {<br>    <br>    @Autowired<br>    private AppointmentRepository appointmentRepository;<br>    <br>    @Autowired<br>    private PatientRepository patientRepository;</pre><pre>    public Appointment createAppointment(<br>        Long patientId, <br>        Appointment appointment<br>    ) {<br>        Patient patient = patientRepository.findById(patientId)<br>            .orElseThrow(() -&gt; new RuntimeException(<br>                &quot;Patient not found&quot;));<br>                <br>        appointment.setPatient(patient);<br>        appointment.setStatus(&quot;Scheduled&quot;);<br>        return appointmentRepository.save(appointment);<br>    }<br>    <br>    // ... other CRUD methods<br>}</pre><p><strong>Key features:</strong></p><ul><li>Proper error handling with descriptive messages</li><li>Validates patient existence before creating appointments</li><li>Sets default status value</li><li>Transactional boundary management</li></ul><h3>4. AppointmentController</h3><pre>@RestController<br>@RequestMapping(&quot;/api/appointments&quot;)<br>public class AppointmentController {<br>    <br>    @Autowired<br>    private AppointmentService appointmentService;</pre><pre>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Appointment&gt; getById(<br>        @PathVariable Long id<br>    ) {<br>        return appointmentService.getAppointmentById(id)<br>            .map(ResponseEntity::ok)<br>            .orElse(ResponseEntity.notFound().build());<br>    }</pre><pre>    @PostMapping<br>    public ResponseEntity&lt;Appointment&gt; create(<br>        @RequestParam Long patientId,<br>        @RequestBody Appointment appointment<br>    ) {<br>        Appointment created = appointmentService<br>            .createAppointment(patientId, appointment);<br>        return ResponseEntity.ok(created);<br>    }<br>    <br>    // ... other endpoints<br>}</pre><h3>5. MCP Tools Integration</h3><pre>@Tool(<br>    name = &quot;schedule_appointment&quot;,<br>    description = &quot;Schedule an appointment for a patient&quot;<br>)<br>public String scheduleAppointment(<br>    @ToolParam(name = &quot;patient_id&quot;, <br>               description = &quot;Numeric ID of the patient&quot;) <br>    Long patientId,<br>    @ToolParam(name = &quot;appointment_date&quot;, <br>               description = &quot;Appointment date and time (ISO-8601)&quot;) <br>    String appointmentDate,<br>    @ToolParam(name = &quot;reason&quot;, <br>               description = &quot;Reason for visit&quot;) <br>    String reason,<br>    @ToolParam(name = &quot;provider&quot;, <br>               description = &quot;Provider name&quot;) <br>    String provider<br>) {<br>    try {<br>        Appointment appt = new Appointment();<br>        appt.setAppointmentDate(<br>            LocalDateTime.parse(appointmentDate));<br>        appt.setReason(reason);<br>        appt.setProvider(provider);<br>        appt.setStatus(&quot;Scheduled&quot;);</pre><pre>        Appointment created = appointmentService<br>            .createAppointment(patientId, appt);<br>        return objectMapper.writeValueAsString(created);<br>    } catch (Exception e) {<br>        return &quot;{\&quot;error\&quot;: \&quot;&quot; + e.getMessage() + &quot;\&quot;}&quot;;<br>    }<br>}</pre><p><strong>MCP integration allows:</strong></p><ul><li>AI assistants (like Claude) to interact with the system</li><li>Natural language appointment scheduling</li><li>Consistent JSON response format</li></ul><h3>6. Updated Patient Entity</h3><pre>@Entity<br>@Table(name = &quot;patients&quot;)<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class Patient {<br>    // ... existing fields ...<br>    <br>    @OneToMany(mappedBy = &quot;patient&quot;, <br>               cascade = CascadeType.ALL, <br>               orphanRemoval = true)<br>    private List&lt;Appointment&gt; appointments = new ArrayList&lt;&gt;();<br>}</pre><p>Properly configured bidirectional relationship with cascade operations.</p><h3>7. Sample Data in DataInitializer</h3><pre>// Sample Appointments for Patient 1<br>Appointment appt1 = new Appointment();<br>appt1.setAppointmentDate(<br>    LocalDateTime.now().plusDays(3).withHour(10).withMinute(0));<br>appt1.setReason(&quot;Blood pressure follow-up&quot;);<br>appt1.setProvider(&quot;Dr. Sarah Johnson&quot;);<br>appt1.setStatus(&quot;Scheduled&quot;);<br>appt1.setPatient(patient1);<br>appointmentRepository.save(appt1);</pre><h3>The Results: Perfect Pattern Adherence</h3><p>What amazed me most wasn’t just that Copilot generated working code — it’s that the code <strong>perfectly matched</strong> our established patterns:</p><p>✅ <strong>Correct annotations</strong>: @Entity, @Table, @Data, @Transactional<br> ✅ <strong>Proper relationships</strong>: @ManyToOne, @OneToMany with correct cascade settings<br> ✅ <strong>Consistent naming</strong>: AppointmentService, AppointmentController<br> ✅ <strong>JSON handling</strong>: @JsonIgnore placed exactly where needed<br> ✅ <strong>Error messages</strong>: Descriptive and following our format<br> ✅ <strong>REST endpoints</strong>: Standard RESTful patterns at /api/appointments<br> ✅ <strong>MCP integration</strong>: Custom @Tool annotations with proper parameters<br> ✅ <strong>Sample data</strong>: Realistic test data with proper relationships</p><h3>The Impact: 10x Productivity Boost</h3><p>Let me break down what would have taken me <strong>2–3 hours</strong> of manual coding:</p><p>Task Manual Time With Copilot Entity creation 15 min 30 sec Repository setup 10 min 20 sec Service layer 30 min 30 sec Controller endpoints 25 min 30 sec MCP tools 20 min 30 sec Entity updates 10 min 20 sec Sample data 15 min 20 sec Testing &amp; debugging 45 min 5 min <strong>Total</strong> <strong>2h 50min</strong> <strong>~15 min</strong></p><p>That’s roughly a <strong>10x improvement</strong> in development speed!</p><h3>Best Practices I Learned</h3><h3>1. Invest Time in Instructions</h3><p>Creating comprehensive instructions upfront pays dividends. My copilot-instructions.md took about 2 hours to write, but I&#39;ve already saved 10+ hours using it.</p><h3>2. Use @workspace Context</h3><p>The @workspace prefix tells Copilot to consider your entire project context, including the instructions file.</p><h3>3. Be Specific About Patterns</h3><p>Instead of saying “create an entity,” I said “create an entity following the pattern in copilot-instructions.md.” This specificity ensures consistency.</p><h3>4. Reference Existing Code</h3><p>“Following the patterns used in Patient, ProgressNote, and CarePlan” gives Copilot concrete examples to learn from.</p><h3>5. Include All Layers</h3><p>Don’t just ask for one component. Request the entire vertical slice (entity, repository, service, controller, tools) to ensure everything integrates properly.</p><h3>6. Specify Relationships Clearly</h3><p>Be explicit about relationship types (@ManyToOne, @OneToMany) and which side owns the relationship.</p><h3>Advanced Techniques</h3><h3>Pattern Recognition</h3><p>Once Copilot learns your patterns, it can:</p><ul><li>Suggest consistent field names</li><li>Apply the same validation approach</li><li>Use identical error handling</li><li>Follow your transaction boundaries</li></ul><h3>Incremental Refinement</h3><p>If the generated code isn’t perfect, you can refine it with follow-up prompts:</p><pre>&quot;Add validation to ensure appointment date is in the future&quot;<br>&quot;Add a method to get upcoming appointments for a patient&quot;<br>&quot;Include pagination in the getAllAppointments endpoint&quot;</pre><h3>Documentation Generation</h3><p>Copilot can even generate JavaDoc comments following your style:</p><pre>&quot;Add JavaDoc comments to all public methods in AppointmentService&quot;</pre><h3>Common Pitfalls to Avoid</h3><h3>1. Vague Instructions</h3><p>❌ “Create an appointment feature”<br> ✅ “Create an Appointment entity with specific fields, following the pattern in copilot-instructions.md”</p><h3>2. Ignoring Context</h3><p>❌ Not using @workspace<br> ✅ Always reference your workspace context</p><h3>3. Incomplete Specifications</h3><p>❌ “Add an entity”<br> ✅ “Add entity, repository, service, controller, and MCP tools”</p><h3>4. Not Reviewing Generated Code</h3><p>Always review the generated code! While Copilot is impressive, it’s not infallible. Check for:</p><ul><li>Proper error handling</li><li>Correct relationship mappings</li><li>Security considerations</li><li>Business logic validation</li></ul><h3>Real-World Testing</h3><p>After generation, I tested the complete feature:</p><pre># Create an appointment<br>curl -X POST http://localhost:8080/api/appointments \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{<br>    &quot;patientId&quot;: 1,<br>    &quot;appointmentDate&quot;: &quot;2025-11-20T10:00:00&quot;,<br>    &quot;reason&quot;: &quot;Annual checkup&quot;,<br>    &quot;provider&quot;: &quot;Dr. Smith&quot;,<br>    &quot;status&quot;: &quot;Scheduled&quot;<br>  }&#39;</pre><pre># Get appointments for a patient<br>curl <a href="http://localhost:8080/api/appointments/by-patient/1">http://localhost:8080/api/appointments/by-patient/1</a></pre><pre># Cancel an appointment<br>curl -X POST <a href="http://localhost:8080/api/appointments/1/cancel">http://localhost:8080/api/appointments/1/cancel</a></pre><p><strong>Everything worked perfectly on the first try!</strong></p><h3>MCP Integration Bonus</h3><p>The MCP tools allow AI assistants like Claude to interact with the system naturally:</p><p><strong>User to Claude</strong>: “Schedule an appointment for John Smith on November 20th at 10 AM for an annual checkup with Dr. Sarah Johnson”</p><p><strong>Claude</strong>: Uses the schedule_appointment tool automatically and confirms: &quot;I&#39;ve scheduled an appointment for John Smith on November 20, 2025, at 10:00 AM with Dr. Sarah Johnson for an annual checkup. The appointment ID is 3.&quot;</p><p>This creates a powerful bridge between natural language interfaces and structured backend systems.</p><h3>Lessons for Your Team</h3><h3>For Individual Developers</h3><ol><li>Create your own copilot-instructions.md for personal projects</li><li>Document patterns as you establish them</li><li>Iterate and refine instructions based on what works</li><li>Share successful patterns with your team</li></ol><h3>For Team Leads</h3><ol><li>Establish project-wide coding standards in a shared instructions file</li><li>Include it in onboarding materials</li><li>Version control it alongside your code</li><li>Regularly update it as patterns evolve</li></ol><h3>For Organizations</h3><ol><li>Consider creating organization-level instruction templates</li><li>Share successful patterns across teams</li><li>Measure productivity improvements</li><li>Balance AI assistance with code review rigor</li></ol><h3>The Future: AI-Assisted Development</h3><p>This experience showed me that AI-assisted development isn’t about replacing developers — it’s about augmenting our capabilities. We still need to:</p><ul><li>Design the architecture</li><li>Define the patterns</li><li>Review the code</li><li>Understand the business logic</li><li>Make critical decisions</li></ul><p>But AI can handle the repetitive, pattern-based implementation work, freeing us to focus on:</p><ul><li>System design</li><li>Business logic</li><li>User experience</li><li>Performance optimization</li><li>Security considerations</li></ul><h3>Conclusion</h3><p>By investing time in creating comprehensive instructions and establishing clear patterns, I transformed GitHub Copilot from a general-purpose code assistant into a specialized team member who understands my project intimately.</p><p>The result? A complete, production-ready feature — including entity, repository, service, controller, MCP tools, and sample data — generated in minutes instead of hours, with perfect adherence to project standards.</p><h3>Try It Yourself</h3><p>Want to replicate this approach? Here’s your action plan:</p><ol><li><strong>Document your patterns</strong>: Create a copilot-instructions.md in your project root</li><li><strong>Include examples</strong>: Reference existing code as patterns to follow</li><li><strong>Be specific</strong>: Detail naming conventions, annotations, and architectural decisions</li><li><strong>Start small</strong>: Test with a simple feature first</li><li><strong>Iterate</strong>: Refine your instructions based on the results</li><li><strong>Share</strong>: Help your team benefit from your learnings</li></ol><p>The complete Patient Care System project with the instructions file is available on <a href="https://github.com/Viktechenthu/patient-care-system">GitHub</a> for you to explore and adapt to your needs.</p><p><em>If you found this helpful, please give it a clap 👏 and follow for more content on AI-assisted development, Spring Boot, and modern software engineering practices!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b278c30c68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building MCP Server with Spring Boot]]></title>
            <link>https://medium.com/@vikalp481/building-mcp-server-with-spring-boot-4e803f4709e2?source=rss-eefda2537786------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e803f4709e2</guid>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mcp-client]]></category>
            <dc:creator><![CDATA[Vikalp]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 18:59:12 GMT</pubDate>
            <atom:updated>2025-11-12T20:52:46.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>From REST APIs to AI-Powered Interactions in One Application</h3><p>If you’ve been following the AI agent revolution, you’ve probably heard about the <strong>Model Context Protocol (MCP)</strong> — Anthropic’s open standard for connecting AI assistants to external data sources. But here’s what most tutorials won’t tell you: <strong>you don’t need a separate Node.js server</strong>. You can build a unified Spring Boot application that serves both traditional REST APIs <em>and</em> an MCP server.</p><p>Let me show you how I built a MCP Server that works seamlessly with Claude Desktop <strong>and</strong> with the intelligent MCP client I detailed in my <a href="https://medium.com/@vikalp481/building-ai-agents-with-mcp-let-your-llm-make-the-callshow-to-build-intelligent-ai-applications-93e3b89ace53">previous article about LLM-driven tool selection</a>.</p><h3>The Problem: Two Servers, Double the Complexity</h3><p>Most MCP tutorials look like this:</p><ol><li>Build your backend in Spring Boot</li><li>Create a separate Node.js MCP server</li><li>Make the MCP server call your Spring Boot APIs</li><li>Configure Claude to talk to Node.js</li><li>Hope everything stays in sync</li></ol><p><strong>This is madness.</strong></p><p>Why maintain two servers, two codebases, and a network hop between them when you can do it all in one place?</p><h3>The Solution: Spring-Native MCP Server</h3><p>Here’s what I built: A <strong>single Spring Boot application</strong> that:</p><ul><li>✅ Serves REST APIs for traditional clients</li><li>✅ Exposes an MCP endpoint for AI assistants</li><li>✅ Shares the same database, services, and business logic</li><li>✅ Requires zero Node.js dependencies</li><li>✅ Works with Claude Desktop AND intelligent MCP clients</li><li>✅ Is production-ready with Spring’s robust ecosystem</li></ul><h3>Architecture Overview</h3><pre>┌─────────────────────────────────────────┐<br>│     Spring Boot MCP Server              │<br>│     (patient-care-system)               │<br>│                                          │<br>│  ┌────────────┐      ┌──────────────┐  │<br>│  │  REST API  │      │  MCP Server  │  │<br>│  │  Endpoints │      │  (/mcp)      │  │<br>│  └─────┬──────┘      └──────┬───────┘  │<br>│        │                     │          │<br>│        └──────┬──────────────┘          │<br>│               │                         │<br>│        ┌──────▼──────┐                 │<br>│        │  Services   │                 │<br>│        │  - Patient  │                 │<br>│        │  - CarePlan │                 │<br>│        │  - Progress │                 │<br>│        └──────┬──────┘                 │<br>│               │                         │<br>│        ┌──────▼──────┐                 │<br>│        │  Database   │                 │<br>│        │  (H2/MySQL) │                 │<br>│        └─────────────┘                 │<br>└─────────────────────────────────────────┘<br>          │              │<br>    ┌─────▼─────┐  ┌────▼──────────┐<br>    │  Postman  │  │  Spring Boot  │<br>    │   /curl   │  │  MCP Client   │<br>    └───────────┘  │  (Intelligent)│<br>                   └────┬──────────┘<br>                        │<br>                   ┌────▼────┐<br>                   │ Ollama  │<br>                   │ LLM     │<br>                   └─────────┘</pre><h3>The Game-Changer: Annotation-Based Tool Definition</h3><p>Instead of manually writing JSON schemas, I created custom annotations that make defining MCP tools as simple as writing regular Spring methods:</p><pre>@Service<br>public class MCPToolService {<br>@Tool(<br>        name = &quot;get_patient_by_name&quot;,<br>        description = &quot;Retrieve patient details by patient name&quot;<br>    )<br>    public String getPatientByName(<br>        @ToolParam(name = &quot;name&quot;, description = &quot;Full name of the patient&quot;) <br>        String name<br>    ) {<br>        Optional&lt;Patient&gt; patient = patientService.getPatientByName(name);<br>        return objectMapper.writeValueAsString(patient.get());<br>    }<br>    <br>    @Tool(<br>        name = &quot;get_all_patients&quot;,<br>        description = &quot;List all patients in the system&quot;<br>    )<br>    public String getAllPatients() {<br>        List&lt;Patient&gt; patients = patientService.getAllPatients();<br>        return objectMapper.writeValueAsString(patients);<br>    }<br>    <br>    @Tool(<br>        name = &quot;get_care_plan&quot;,<br>        description = &quot;Get the care plan for a specific patient&quot;<br>    )<br>    public String getCarePlan(<br>        @ToolParam(name = &quot;patient_id&quot;, description = &quot;Numeric ID of the patient&quot;) <br>        Long patientId<br>    ) {<br>        Optional&lt;CarePlan&gt; carePlan = patientService.getCarePlanByPatientId(patientId);<br>        return objectMapper.writeValueAsString(carePlan.get());<br>    }<br>}</pre><p><strong>That’s it.</strong> The framework automatically:</p><ul><li>Discovers all @Tool annotated methods</li><li>Generates JSON schemas from @ToolParam annotations</li><li>Handles type conversion and validation</li><li>Exposes them through the MCP endpoint</li></ul><h3>Key Components</h3><h3>1. Custom Annotations</h3><p>Two simple annotations make everything work:</p><pre>@Target(ElementType.METHOD)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface Tool {<br>    String name();<br>    String description();<br>}</pre><pre>@Target(ElementType.PARAMETER)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface ToolParam {<br>    String name();<br>    String description();<br>    boolean required() default true;<br>}</pre><h3>2. MCP Server Component</h3><p>The MCPServer class uses reflection to discover and invoke tools:</p><pre>@Component<br>public class MCPServer {<br>    <br>    public void initializeTools() {<br>        // Scan all Spring beans for @Tool annotated methods<br>        String[] beanNames = applicationContext.getBeanDefinitionNames();<br>        for (String beanName : beanNames) {<br>            Object bean = applicationContext.getBean(beanName);<br>            for (Method method : bean.getClass().getDeclaredMethods()) {<br>                if (method.isAnnotationPresent(Tool.class)) {<br>                    // Register tool with metadata<br>                    registerTool(method, bean);<br>                }<br>            }<br>        }<br>    }<br>    <br>    public String callTool(String toolName, Map&lt;String, Object&gt; arguments) {<br>        ToolMetadata metadata = tools.get(toolName);<br>        Object result = metadata.method.invoke(metadata.bean, args);<br>        return result.toString();<br>    }<br>}</pre><h3>3. MCP Controller</h3><p>A simple REST controller handles the JSON-RPC 2.0 protocol:</p><pre>@RestController<br>@RequestMapping(&quot;/mcp&quot;)<br>public class MCPController {<br>    <br>    @PostMapping<br>    public ResponseEntity&lt;Map&lt;String, Object&gt;&gt; handleMCPRequest(<br>        @RequestBody Map&lt;String, Object&gt; request<br>    ) {<br>        String method = (String) request.get(&quot;method&quot;);<br>        <br>        switch (method) {<br>            case &quot;initialize&quot;:<br>                return handleInitialize();<br>            case &quot;tools/list&quot;:<br>                return handleToolsList();<br>            case &quot;tools/call&quot;:<br>                return handleToolsCall(request);<br>        }<br>    }<br>}</pre><h3>Available MCP Tools</h3><p>This system exposes <strong>8 powerful tools</strong> through the MCP interface:</p><h3>Patient Management</h3><ul><li>get_patient_by_name - Search patients by full name</li><li>get_patient_by_id - Lookup patients by numeric ID</li><li>get_all_patients - List all patients in the system</li><li>create_patient - Create new patient records</li></ul><h3>Clinical Data</h3><ul><li>get_progress_notes - View medical progress notes for a patient</li><li>add_progress_note - Document new observations and treatments</li><li>get_care_plan - Retrieve treatment plans</li><li>update_care_plan - Modify care plans with new goals and interventions</li></ul><p>Each tool is automatically documented with parameters, descriptions, and types!</p><h3>Using This MCP Server</h3><p>You have <strong>two options</strong> for using this MCP server:</p><h3>Option 1: With Claude Desktop (Simple)</h3><p>The bridge to Claude is just a simple shell script:</p><pre>#!/bin/bash<br># mcp-server.sh</pre><pre>while IFS= read -r line; do<br>  response=$(curl -s -X POST <a href="http://localhost:8080/mcp">http://localhost:8080/mcp</a> \<br>    -H &quot;Content-Type: application/json&quot; \<br>    -d &quot;$line&quot;)<br>  echo &quot;$response&quot;<br>done</pre><p>Configure Claude Desktop:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;patient-care&quot;: {<br>      &quot;command&quot;: &quot;/absolute/path/to/mcp-server.sh&quot;<br>    }<br>  }<br>}</pre><h3>Option 2: With Intelligent MCP Client (Recommended)</h3><p>This is where things get <strong>really powerful</strong>. Instead of using Claude Desktop, use the intelligent MCP client I built in my <a href="https://medium.com/@vikalp481/building-ai-agents-with-mcp-let-your-llm-make-the-callshow-to-build-intelligent-ai-applications-93e3b89ace53">previous article</a>.</p><p><strong>Why use the intelligent client?</strong></p><ul><li>🧠 <strong>LLM decides when to call tools</strong> — No pattern matching required</li><li>🎯 <strong>Natural language understanding</strong> — Ask questions any way you want</li><li>🔄 <strong>Streaming responses</strong> — Real-time AI responses</li><li>🎨 <strong>Beautiful UI</strong> — Modern web interface with chat history</li><li>🔧 <strong>Multiple sessions</strong> — Manage different conversations</li><li>📊 <strong>Tool visibility</strong> — See all available MCP tools in the sidebar</li></ul><h3>Setting Up the Complete System</h3><p>Here’s how to connect the MCP server with the intelligent client:</p><h3>Step 1: Start the MCP Server</h3><pre># Clone the patient care system<br>git clone https://github.com/Viktechenthu/patient-care-system<br>cd patient-care-system</pre><pre># Build and run<br>mvn clean install<br>mvn spring-boot:run</pre><p>The server starts on <a href="http://localhost:8080/">http://localhost:8080</a></p><h3>Step 2: Configure the MCP Client</h3><p>In your Spring Boot MCP client’s application.yml:</p><pre># MCP Server Configuration<br>mcp:<br>  server:<br>    url: http://localhost:8080/mcp<br>    timeout: 30000</pre><pre># Ollama Configuration<br>spring:<br>  ai:<br>    ollama:<br>      base-url: <a href="http://localhost:11434/">http://localhost:11434</a><br>      chat:<br>        options:<br>          model: llama2<br>          temperature: 0.8</pre><h3>Step 3: Start the MCP Client</h3><pre># Clone the MCP client<br>git clone https://github.com/Viktechenthu/spring-mcp-client<br>cd spring-mcp-client</pre><pre># Build and run<br>mvn clean install<br>mvn spring-boot:run</pre><p>The client starts on <a href="http://localhost:8081/">http://localhost:8081</a></p><h3>Step 4: Start Chatting!</h3><p>Open your browser to http://localhost:8081 and try these queries:</p><p><strong>Natural Language Queries:</strong></p><ul><li><em>“Show me all patients in the system”</em></li><li><em>“Get details for patient John Smith”</em></li><li><em>“What’s the care plan for patient ID 1?”</em></li><li><em>“Show me progress notes for Mary Johnson”</em></li><li><em>“Update the care plan for patient 2 with new goals”</em></li></ul><h3>How the Magic Happens</h3><p>Let me show you the complete flow:</p><pre>User: &quot;Show me all patients&quot;<br>    ↓<br>MCP Client: Asks LLM &quot;Should I call a tool?&quot;<br>    ↓<br>LLM: {&quot;action&quot;: &quot;call&quot;, &quot;tool&quot;: &quot;get_all_patients&quot;, &quot;arguments&quot;: {}}<br>    ↓<br>MCP Client: POST http://localhost:8080/mcp<br>    {<br>      &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>      &quot;method&quot;: &quot;tools/call&quot;,<br>      &quot;params&quot;: {<br>        &quot;name&quot;: &quot;get_all_patients&quot;,<br>        &quot;arguments&quot;: {}<br>      }<br>    }<br>    ↓<br>MCP Server: Invokes @Tool annotated method<br>    ↓<br>PatientService: Fetches from database<br>    ↓<br>MCP Server: Returns JSON patient data<br>    ↓<br>MCP Client: LLM formats the response<br>    ↓<br>User: Sees beautifully formatted patient list</pre><h3>The Intelligent Client Advantage</h3><p>As I explained in my <a href="https://medium.com/@vikalp481/building-ai-agents-with-mcp-let-your-llm-make-the-callshow-to-build-intelligent-ai-applications-93e3b89ace53">previous article</a>, the intelligent MCP client uses <strong>LLM-driven tool selection</strong>:</p><pre>// The client asks the LLM to decide which tool to call<br>private ToolDecision decideTool(String userMessage) {<br>    List&lt;McpTool&gt; tools = mcpClientService.listTools().block();<br>    <br>    String prompt = buildToolDecisionPrompt(userMessage, tools);<br>    String llmResponse = chatClient.prompt(prompt).call().content();<br>    <br>    return parseToolDecision(llmResponse);<br>}</pre><pre>// Then executes the tool<br>if (decision != null &amp;&amp; decision.shouldCallTool()) {<br>    String toolResult = mcpClientService.callTool(<br>        decision.toolName, <br>        decision.arguments<br>    ).block();<br>    <br>    // LLM formats the response naturally<br>    streamFormattedResponse(userMessage, toolResult, chunkConsumer);<br>}</pre><p><strong>No pattern matching. No regex. Just pure LLM intelligence.</strong></p><h3>Real-World Examples</h3><h3>Example 1: Finding a Patient</h3><p><strong>User Input:</strong></p><pre>&quot;I need information about patient John Smith&quot;</pre><p><strong>What Happens:</strong></p><ol><li>LLM analyzes: “This needs patient data by name”</li><li>Decides to call: get_patient_by_name with {&quot;name&quot;: &quot;John Smith&quot;}</li><li>MCP Server executes the tool</li><li>Returns patient data</li><li>LLM formats: “Here’s John Smith’s information: [formatted data]”</li></ol><h3>Example 2: Complex Query</h3><p><strong>User Input:</strong></p><pre>&quot;Show me the care plan for patient 1 and tell me if there are any progress notes&quot;</pre><p><strong>What Happens:</strong></p><ol><li>LLM identifies two actions needed</li><li>First call: get_care_plan with {&quot;patient_id&quot;: 1}</li><li>Second call: get_progress_notes with {&quot;patient_id&quot;: 1}</li><li>LLM synthesizes both results</li><li>Returns: Comprehensive overview of patient’s care</li></ol><h3>Why This Architecture Wins</h3><h3>1. Single MCP Server, Multiple Clients</h3><p>Your MCP server can serve:</p><ul><li>Claude Desktop</li><li>Your intelligent MCP client</li><li>Any other MCP-compatible client</li><li>Future AI assistants</li></ul><h3>2. Type Safety</h3><p>Java’s strong typing catches errors at compile time, not runtime.</p><h3>3. Dependency Injection</h3><p>Use Spring’s IoC container for all your services. No manual wiring.</p><h3>4. Direct Database Access</h3><p>MCP tools directly use JPA repositories — no HTTP overhead between client and server.</p><h3>5. Production Features</h3><p>Get Spring Boot’s monitoring, security, and deployment tools out of the box.</p><h3>6. Easy Testing</h3><p>Use Spring Boot Test framework for both REST and MCP endpoints.</p><h3>The Developer Experience</h3><p>Here’s what adding a new tool looks like:</p><p><strong>Before (Traditional Approach):</strong></p><ol><li>Write tool logic in Spring Boot</li><li>Create REST endpoint</li><li>Update MCP server configuration</li><li>Manually define JSON schema</li><li>Update client to know about new tool</li><li>Handle errors in multiple places</li><li>Deploy everything</li></ol><p><strong>After (Annotation-Based MCP):</strong></p><ol><li>Add @Tool annotation to your method</li><li>Restart server</li><li>Client automatically discovers the new tool</li><li>Done.</li></ol><pre>// Just add this to your service class<br>@Tool(<br>    name = &quot;schedule_appointment&quot;,<br>    description = &quot;Schedule a new appointment for a patient&quot;<br>)<br>public String scheduleAppointment(<br>    @ToolParam(name = &quot;patient_id&quot;, description = &quot;Patient ID&quot;) Long patientId,<br>    @ToolParam(name = &quot;date&quot;, description = &quot;Appointment date (YYYY-MM-DD)&quot;) String date,<br>    @ToolParam(name = &quot;time&quot;, description = &quot;Appointment time (HH:MM)&quot;) String time<br>) {<br>    // Your logic here<br>}</pre><p>The LLM-powered client will automatically:</p><ul><li>Discover the new tool</li><li>Understand when to call it</li><li>Extract parameters from user queries</li><li>Present results naturally</li></ul><h3>Advanced Features</h3><h3>Automatic Schema Generation</h3><p>The framework generates complete schemas automatically:</p><pre>{<br>  &quot;name&quot;: &quot;get_patient_by_name&quot;,<br>  &quot;description&quot;: &quot;Retrieve patient details by patient name&quot;,<br>  &quot;inputSchema&quot;: {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>      &quot;name&quot;: {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;description&quot;: &quot;Full name of the patient&quot;<br>      }<br>    },<br>    &quot;required&quot;: [&quot;name&quot;]<br>  }<br>}</pre><h3>Tool Discovery in UI</h3><p>The intelligent client shows all available tools in the sidebar:</p><pre>Available Tools:<br>├─ get_patient_by_name<br>├─ get_patient_by_id  <br>├─ get_all_patients<br>├─ get_progress_notes<br>├─ get_care_plan<br>└─ update_care_plan</pre><p>Users can see what the system can do at a glance!</p><h3>Real-World Impact</h3><p>After implementing this complete system:</p><ul><li><strong>95% less code</strong> compared to separate servers with pattern matching</li><li><strong>Zero network latency</strong> within MCP server (direct method calls)</li><li><strong>Single Spring Boot deployment</strong> for MCP server</li><li><strong>Natural language queries</strong> — users ask questions naturally</li><li><strong>Faster development</strong> — new tools in minutes, automatic discovery</li></ul><h3>Lessons Learned</h3><h3>1. Separation of Concerns</h3><p>Keep MCP server (data/tools) separate from MCP client (intelligence/UI).</p><h3>2. Let the LLM Decide</h3><p>Don’t hardcode tool selection logic. Let the LLM understand intent.</p><h3>3. Annotations Are Powerful</h3><p>Custom annotations make your code self-documenting and reduce boilerplate.</p><h3>4. Single Responsibility</h3><ul><li>MCP Server: Expose tools and data</li><li>MCP Client: Understand user intent and present results</li><li>LLM: Bridge the gap with intelligence</li></ul><h3>5. Developer Experience Matters</h3><p>Make it easy to add features. If adding a new tool is hard, something’s wrong.</p><h3>What’s Next?</h3><p>The possibilities are endless:</p><ul><li><strong>Multi-model support</strong> — Use different LLMs for different tasks</li><li><strong>Tool composition</strong> — Let LLMs chain multiple tools automatically</li><li><strong>Smart caching</strong> — Remember previous queries</li><li><strong>Real-time collaboration</strong> — Multiple users, shared sessions</li><li><strong>Voice interface</strong> — Already has speech recognition built-in!</li><li><strong>Mobile app</strong> — Responsive design ready for mobile</li></ul><h3>Complete Example: Adding a New Feature</h3><p>Let’s say you want to add appointment scheduling:</p><p><strong>Step 1: Add to MCP Server</strong></p><pre>@Tool(<br>    name = &quot;schedule_appointment&quot;,<br>    description = &quot;Schedule a new appointment for a patient&quot;<br>)<br>public String scheduleAppointment(<br>    @ToolParam(name = &quot;patient_id&quot;, description = &quot;Patient ID&quot;) Long patientId,<br>    @ToolParam(name = &quot;appointment_date&quot;, description = &quot;Date (YYYY-MM-DD)&quot;) String date,<br>    @ToolParam(name = &quot;appointment_time&quot;, description = &quot;Time (HH:MM)&quot;) String time,<br>    @ToolParam(name = &quot;provider&quot;, description = &quot;Healthcare provider name&quot;) String provider<br>) {<br>    Appointment appointment = appointmentService.schedule(patientId, date, time, provider);<br>    return objectMapper.writeValueAsString(appointment);<br>}</pre><p><strong>Step 2: Restart MCP Server</strong></p><pre>mvn spring-boot:run</pre><p><strong>Step 3: That’s it!</strong></p><p>Now users can say:</p><ul><li><em>“Schedule an appointment for patient 1 tomorrow at 2pm with Dr. Smith”</em></li><li><em>“Book patient John Smith for next Monday at 10am”</em></li><li><em>“I need to see Dr. Johnson on Friday afternoon”</em></li></ul><p>The LLM will:</p><ol><li>Understand the intent</li><li>Extract parameters (patient ID/name, date, time, provider)</li><li>Call the right tool</li><li>Present confirmation naturally</li></ol><p><strong>Zero code changes in the client!</strong></p><h3>Try It Yourself</h3><h3>Complete Setup Guide</h3><p><strong>1. Clone both repositories:</strong></p><pre>git clone https://github.com/Viktechenthu/patient-care-system<br>git clone https://github.com/Viktechenthu/spring-mcp-client</pre><p><strong>2. Start Ollama (for the intelligent client):</strong></p><pre>ollama serve<br>ollama pull llama2</pre><p><strong>3. Start the MCP Server:</strong></p><pre>cd patient-care-system<br>mvn spring-boot:run<br># Server running on http://localhost:8080</pre><p><strong>4. Start the MCP Client:</strong></p><pre>cd spring-mcp-client<br>mvn spring-boot:run<br># Client running on http://localhost:8081</pre><p><strong>5. Open your browser:</strong></p><pre>http://localhost:8081</pre><p><strong>6. Start chatting!</strong></p><pre>&quot;Show me all patients&quot;<br>&quot;Get details for John Smith&quot;<br>&quot;What&#39;s the care plan for patient 1?&quot;</pre><h3>Key Takeaways</h3><p>🎯 <strong>Spring Boot can do it all</strong> — MCP server with REST APIs in one app<br> 🧠 <strong>LLMs make the decisions</strong> — No pattern matching required<br> 📝 <strong>Annotations simplify everything</strong> — Define tools with @Tool<br> ⚡ <strong>Direct method invocation</strong> - Zero overhead within server<br> 🚀 <strong>Quick to extend</strong> - Add new tools in minutes</p><h3>The Bottom Line</h3><p>Building AI-powered applications doesn’t have to be complex. With:</p><ol><li><strong>Spring Boot MCP Server</strong> — Annotation-based tools</li><li><strong>Intelligent MCP Client</strong> — LLM-driven tool selection (<a href="https://medium.com/@vikalp481/building-ai-agents-with-mcp-let-your-llm-make-the-callshow-to-build-intelligent-ai-applications-93e3b89ace53">see my article</a>)</li><li><strong>Local LLM</strong> — Privacy-focused with Ollama</li></ol><p>You get a <strong>complete AI system</strong> that:</p><ul><li>Understands natural language</li><li>Automatically calls the right tools</li><li>Presents information beautifully</li><li>Scales with your business</li></ul><p>The future of enterprise AI is here, and it’s written in Java.</p><p><strong>Questions? Comments? Built something cool with this?</strong> Drop a comment below! I’d love to hear about your experience.</p><p><em>Enjoyed this article? Follow me for more content on AI engineering, Spring Boot, and building Scalable systems.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e803f4709e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI Agents with MCP: Spring]]></title>
            <link>https://medium.com/@vikalp481/building-ai-agents-with-mcp-let-your-llm-make-the-callshow-to-build-intelligent-ai-applications-93e3b89ace53?source=rss-eefda2537786------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e3b89ace53</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mcp-client]]></category>
            <dc:creator><![CDATA[Vikalp]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 21:25:09 GMT</pubDate>
            <atom:updated>2025-11-12T23:08:38.519Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been building AI applications, you’ve probably hit this wall: your chatbot is smart, but it can’t <em>do</em> anything. It can’t check a database, call an API, or retrieve real-time information. You’re stuck writing endless if statements and regex patterns to figure out what the user wants.</p><p>What if your LLM could decide for itself when to call functions? What if it could intelligently determine “Oh, the user wants patient data, I should call the get_patient_by_id function&quot;?</p><p>That’s exactly what I built, and I’m going to show you how.</p><h3>The Problem: Dumb Pattern Matching vs. Smart AI</h3><p>Most developers start with something like this:</p><p>java</p><pre>if (message.contains(&quot;all patients&quot;) || message.contains(&quot;list patients&quot;)) {<br>    return callApi(&quot;get_all_patients&quot;);<br>}<br>else if (message.matches(&quot;patient.*?(\\d+)&quot;)) {<br>    String id = extractId(message);<br>    return callApi(&quot;get_patient_by_id&quot;, id);<br>}</pre><p>This approach has major problems:</p><ul><li>🚫 Only works for exact phrases you anticipated</li><li>🚫 Breaks with natural language variations</li><li>🚫 Requires constant maintenance as you add features</li><li>🚫 Doesn’t scale beyond a handful of commands</li></ul><h3>The Solution: LLM-Driven Tool Selection</h3><p>Instead of pattern matching, let the LLM decide what to do:</p><pre>User: &quot;Can you show me info on patient 42?&quot;<br>↓<br>LLM: &quot;This requires get_patient_by_id with patient_id=42&quot;<br>↓<br>System: Calls the function automatically<br>↓<br>LLM: Formats and presents the data naturally</pre><h3>Introducing MCP: The Missing Link</h3><p><strong>Model Context Protocol (MCP)</strong> is an open standard that lets AI applications connect to external data sources and tools. Think of it as a universal adapter between your LLM and… everything else.</p><p>With MCP, your tools are described in a standard format that any LLM can understand:</p><p>json</p><pre>{<br>  &quot;name&quot;: &quot;get_patient_by_id&quot;,<br>  &quot;description&quot;: &quot;Retrieve patient information by ID&quot;,<br>  &quot;parameters&quot;: {<br>    &quot;patient_id&quot;: &quot;number&quot;<br>  }<br>}</pre><h3>The Architecture</h3><p>Here’s how it all fits together:</p><pre>User Message<br>    ↓<br>1. LLM analyzes: &quot;Do I need to call a tool?&quot;<br>    ↓<br>2. LLM returns: {&quot;action&quot;: &quot;call&quot;, &quot;tool&quot;: &quot;get_patient_by_id&quot;, &quot;arguments&quot;: {&quot;patient_id&quot;: 42}}<br>    ↓<br>3. System calls MCP server → Gets data<br>    ↓<br>4. LLM formats the response naturally<br>    ↓<br>User sees formatted answer</pre><h3>Implementation: The Code That Makes It Work</h3><h3>Step 1: Let the LLM Decide</h3><p>Instead of pattern matching, ask the LLM what to do:</p><p>java</p><pre>private ToolDecision decideTool(String userMessage) {<br>    // Get available tools from MCP server<br>    List&lt;McpTool&gt; tools = mcpClientService.listTools().block();<br>    <br>    // Build a prompt with tool descriptions<br>    String prompt = buildToolDecisionPrompt(userMessage, tools);<br>    <br>    // Ask the LLM<br>    String llmResponse = chatClient.prompt(prompt).call().content();<br>    <br>    // Parse the decision<br>    return parseToolDecision(llmResponse);<br>}</pre><h3>Step 2: The Prompt That Works</h3><p>The key is a well-structured prompt:</p><p>java</p><pre>private String buildToolDecisionPrompt(String userMessage, List&lt;McpTool&gt; tools) {<br>    StringBuilder sb = new StringBuilder();<br>    sb.append(&quot;Available tools:\n&quot;);<br>    <br>    for (McpTool tool : tools) {<br>        sb.append(&quot;{\n&quot;);<br>        sb.append(&quot;  \&quot;name\&quot;: \&quot;&quot;).append(tool.getName()).append(&quot;\&quot;,\n&quot;);<br>        sb.append(&quot;  \&quot;description\&quot;: \&quot;&quot;).append(tool.getDescription()).append(&quot;\&quot;,\n&quot;);<br>        sb.append(&quot;  \&quot;parameters\&quot;: &quot;).append(tool.getParameters()).append(&quot;\n&quot;);<br>        sb.append(&quot;}\n\n&quot;);<br>    }<br>    <br>    sb.append(&quot;User request: \&quot;&quot;).append(userMessage).append(&quot;\&quot;\n\n&quot;);<br>    sb.append(&quot;Respond with JSON:\n&quot;);<br>    sb.append(&quot;To call: {\&quot;action\&quot;: \&quot;call\&quot;, \&quot;tool\&quot;: \&quot;name\&quot;, \&quot;arguments\&quot;: {...}}\n&quot;);<br>    sb.append(&quot;If not needed: {\&quot;action\&quot;: \&quot;none\&quot;}\n&quot;);<br>    <br>    return sb.toString();<br>}</pre><h3>Step 3: Execute and Format</h3><p>Once the LLM decides, execute the tool and let the LLM format the response:</p><p>java</p><pre>public void chatStream(String userMessage, Consumer&lt;String&gt; chunkConsumer) {<br>    // Let LLM decide<br>    ToolDecision decision = decideTool(userMessage);<br>    <br>    if (decision != null &amp;&amp; decision.shouldCallTool()) {<br>        // Call the tool<br>        String toolResult = mcpClient.callTool(<br>            decision.toolName, <br>            decision.arguments<br>        ).block();<br>        <br>        // Ask LLM to format it naturally<br>        streamFormattedResponse(userMessage, toolResult, chunkConsumer);<br>    } else {<br>        // Regular chat<br>        streamRegularResponse(userMessage, chunkConsumer);<br>    }<br>}</pre><h3>Real-World Examples</h3><h3>Before (Pattern Matching):</h3><pre>User: &quot;Show me patient John Smith&quot;<br>System: *doesn&#39;t match any pattern* &quot;I don&#39;t understand&quot;</pre><pre>User: &quot;patient 123&quot;<br>System: ✓ Matches! Calls get_patient_by_id(123)</pre><h3>After (LLM-Driven):</h3><pre>User: &quot;Show me patient John Smith&quot;<br>LLM: Calls get_patient_by_name(&quot;John Smith&quot;) ✓</pre><pre>User: &quot;What&#39;s the care plan for patient 42?&quot;<br>LLM: Calls get_care_plan(42) ✓</pre><pre>User: &quot;I need info on patient ID 5&quot;<br>LLM: Calls get_patient_by_id(5) ✓</pre><pre>User: &quot;Tell me about all patients&quot;<br>LLM: Calls get_all_patients() ✓</pre><h3>Why This Matters</h3><p><strong>1. Natural Language Understanding</strong> Users can ask however they want. The LLM understands intent, not just keywords.</p><p><strong>2. Zero Maintenance</strong> Add new tools to your MCP server, and the LLM automatically knows how to use them.</p><p><strong>3. Context Awareness</strong> The LLM considers conversation history when deciding what to call.</p><p><strong>4. Self-Documenting</strong> Your tools describe themselves. No more outdated documentation.</p><h3>The “Aha!” Moment</h3><p>The breakthrough came when I realized: <strong>Stop telling the LLM what to do. Ask it what needs to be done.</strong></p><p>Instead of:</p><pre>&quot;If user says X, call function Y&quot;</pre><p>Use:</p><pre>&quot;Here are the available functions. What should I call for this request?&quot;</pre><h3>Works with Any LLM</h3><p>The beauty of this approach? It works with:</p><ul><li>✅ Ollama (local models)</li><li>✅ OpenAI GPT-4</li><li>✅ Azure OpenAI</li><li>✅ Anthropic Claude</li><li>✅ Any LLM with chat completion</li></ul><p>No special function-calling API required. Just standard chat completions.</p><h3>Getting Started</h3><ol><li><strong>Set up an MCP server</strong> with your tools/APIs</li><li><strong>Describe your tools</strong> in MCP format</li><li><strong>Let the LLM decide</strong> which tools to call</li><li><strong>Execute and format</strong> the results</li></ol><p>The full code is available in my <a href="https://github.com/Viktechenthu/springMCPClient">GitHub repository</a>.</p><h3>Key Takeaways</h3><ul><li>🎯 <strong>LLMs are smart enough</strong> to decide when to use tools</li><li>🔧 <strong>MCP provides the standard</strong> for describing tools</li><li>🚀 <strong>No pattern matching</strong> required</li><li>🌍 <strong>Works with any LLM</strong> (not just OpenAI)</li><li>📈 <strong>Scales infinitely</strong> — just add more tools</li></ul><h3>What’s Next?</h3><p>This is just the beginning. Imagine:</p><ul><li>AI agents that autonomously complete multi-step tasks</li><li>Chatbots that seamlessly integrate with any API</li><li>Personal assistants that actually <em>assist</em></li></ul><p>The future of AI isn’t just smarter models — it’s models that can <strong>do things</strong>.</p><p><strong>Want to build your own?</strong> Check out the <a href="https://medium.com/@vikalp481/building-mcp-server-with-spring-boot-4e803f4709e2">Model Context Protocol</a> and start building AI that doesn’t just talk, but <em>acts</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e3b89ace53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>