Showing posts with label AI. Show all posts
Showing posts with label AI. Show all posts

Wednesday, September 9, 2026

Build an AI Agent with C# and .NET 8

In the previous article, we learned what an AI Agent is, how the agent loop works, and how agents can use tools to accomplish tasks.

Now let's build a simple AI Agent using C# and .NET 8.

The goal of this tutorial is not to build a complicated autonomous system. Instead, we will create a simple agent that demonstrates the core concepts:

  • LLM integration
  • Tool calling
  • Agent decision-making
  • Tool execution
  • Observations
  • Agent loop

Once you understand this basic architecture, you can extend it with RAG, MCP, databases, APIs, memory, and multiple tools.


What We Are Building

We will create a simple customer-support AI agent.

The user will be able to ask something like:

"What is the status of order 1001?"

The agent will decide that it needs to call an order lookup tool.

User
 ↓
AI Agent
 ↓
LLM
 ↓
Choose Tool
 ↓
get_order_status()
 ↓
Order System
 ↓
Tool Result
 ↓
LLM
 ↓
Final Answer

Prerequisites

Before starting, make sure you have:

  • .NET 8 SDK
  • Visual Studio 2022 or Visual Studio Code
  • Basic C# knowledge
  • Basic understanding of APIs and JSON
  • Access to an LLM API or a locally running compatible model

You can also use a local LLM if your model and client support tool/function calling.


Step 1: Create a .NET 8 Console Application

Open a terminal and create a new console application:

dotnet new console -n SimpleAiAgent
cd SimpleAiAgent

Open the project in Visual Studio or Visual Studio Code.


Step 2: Install the OpenAI .NET SDK

For this example, we will use the official OpenAI .NET client.

Install the NuGet package:

dotnet add package OpenAI

The same general architecture can also be adapted to other LLM providers that support compatible tool/function calling.


Step 3: Configure the API Key

For a quick local test, you can configure your API key as an environment variable.

On Windows:

setx OPENAI_API_KEY "YOUR_API_KEY"

Restart your terminal after setting the environment variable.

Security Note: Never commit API keys directly into source control. Use environment variables, user secrets, managed identity, or a secure secret-management solution for production applications.

Step 4: Create an Order Service

Let's create a simple C# service that represents an external business system.

Create a class named OrderService.cs:

public class OrderService
{
    public string GetOrderStatus(int orderId)
    {
        if (orderId == 1001)
        {
            return "Order 1001 is shipped and is expected to arrive tomorrow.";
        }

        if (orderId == 1002)
        {
            return "Order 1002 is being processed.";
        }

        return $"Order {orderId} was not found.";
    }
}

In a real application, this method could call:

  • A REST API
  • SQL Server
  • An ERP system
  • An order-management system
  • A microservice

The AI agent does not need to know how the data is retrieved. It only needs a well-defined tool.


Step 5: Define the Agent Tool

We need to expose the order lookup operation to the LLM.

The tool definition tells the model:

  • What the tool is called
  • What the tool does
  • What parameters it accepts

A conceptual tool definition looks like:

Tool Name:
get_order_status

Description:
Gets the current status of a customer order.

Parameter:
orderId - The order number to look up.

The description is important because the model uses it to determine when the tool should be used.


Step 6: Create the Tool Definition in C#

Using the OpenAI .NET SDK, we can describe the function to the model.

using OpenAI.Chat;

var getOrderStatusTool = ChatTool.CreateFunctionTool(
    functionName: "get_order_status",
    functionDescription: "Gets the current status of a customer order.",
    functionParameters: BinaryData.FromString("""
    {
        "type": "object",
        "properties": {
            "orderId": {
                "type": "integer",
                "description": "The order number to look up."
            }
        },
        "required": ["orderId"]
    }
    """)
);

The JSON schema tells the model what arguments the function expects.


Step 7: Create the Chat Client

Now we can create the chat client.

using OpenAI.Chat;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("OPENAI_API_KEY is not configured.");

ChatClient client = new(
    model: "gpt-4o-mini",
    apiKey: apiKey
);
Note: Model names and availability can change over time. Use a model that is currently available to your account and supports the capabilities required by your application.

Step 8: Send the User Request

Let's start with a simple request:

string userMessage =
    "What is the status of order 1001?";

We now send the message to the LLM along with the tool definition.

List messages =
[
    new UserChatMessage(userMessage)
];

ChatCompletionOptions options = new()
{
    Tools = { getOrderStatusTool }
};

ChatCompletion completion =
    client.CompleteChat(messages, options);

Step 9: Detect a Tool Call

The model may determine that it needs to use the get_order_status tool.

We can inspect the response:

if (completion.FinishReason == ChatFinishReason.ToolCalls)
{
    Console.WriteLine("The agent requested a tool.");
}

The model can return a tool call containing the function name and arguments.

Conceptually, the response may look like:

Function:
get_order_status

Arguments:
{
    "orderId": 1001
}

Step 10: Execute the Tool

Now our C# application needs to execute the requested function.

OrderService orderService = new();

string result =
    orderService.GetOrderStatus(1001);

Console.WriteLine(result);

The output will be:

Order 1001 is shipped and is expected to arrive tomorrow.

This is an important concept:

The LLM does not directly execute your C# method. The application receives the tool request, validates it, executes the appropriate code, and sends the result back to the model.

Step 11: Send the Tool Result Back to the LLM

After executing the tool, the application sends the result back to the model.

messages.Add(new AssistantChatMessage(completion));

messages.Add(
    new ToolChatMessage(
        toolCallId,
        result
    )
);

completion = client.CompleteChat(messages, options);

The LLM now has the information returned by the tool.


Step 12: Generate the Final Answer

The model can now generate a natural-language response.

Console.WriteLine(completion.Content[0].Text);

Example:

Order 1001 has been shipped and is expected
to arrive tomorrow.

The complete flow is:

User
 ↓
"What is the status of order 1001?"
 ↓
LLM
 ↓
Tool Call
 ↓
get_order_status(1001)
 ↓
C# OrderService
 ↓
Order System
 ↓
Tool Result
 ↓
LLM
 ↓
Final Answer

Step 13: Build the Agent Loop

A real agent may need to perform more than one action.

For example:

User:
"Find order 1001 and tell me whether
it is likely to arrive tomorrow."

Agent:

1. Get order status
2. Get shipment information
3. Check delivery estimate
4. Analyze results
5. Generate answer

Therefore, we need a loop.

while (true)
{
    Send messages to LLM

    if (LLM requests a tool)
    {
        Execute tool
        Add tool result to messages
        Continue
    }

    Return final response
    break;
}

This is the foundation of an agent loop.


Complete Simplified Agent Example

The following example demonstrates the overall architecture:

using OpenAI.Chat;

string apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("OPENAI_API_KEY is not configured.");

ChatClient client = new(
    model: "gpt-4o-mini",
    apiKey: apiKey
);

OrderService orderService = new();

var tool = ChatTool.CreateFunctionTool(
    functionName: "get_order_status",
    functionDescription: "Gets the current status of a customer order.",
    functionParameters: BinaryData.FromString("""
    {
        "type": "object",
        "properties": {
            "orderId": {
                "type": "integer",
                "description": "The order number."
            }
        },
        "required": ["orderId"]
    }
    """)
);

List messages =
[
    new UserChatMessage(
        "What is the status of order 1001?"
    )
];

ChatCompletionOptions options = new()
{
    Tools = { tool }
};

while (true)
{
    ChatCompletion completion =
        client.CompleteChat(messages, options);

    if (completion.FinishReason == ChatFinishReason.ToolCalls)
    {
        messages.Add(new AssistantChatMessage(completion));

        foreach (ChatToolCall toolCall in completion.ToolCalls)
        {
            if (toolCall.FunctionName == "get_order_status")
            {
                int orderId =
                    int.Parse(toolCall.FunctionArguments
                        .ToString()
                        .Replace("{\"orderId\":", "")
                        .Replace("}", ""));

                string result =
                    orderService.GetOrderStatus(orderId);

                messages.Add(
                    new ToolChatMessage(
                        toolCall.Id,
                        result
                    )
                );
            }
        }

        continue;
    }

    Console.WriteLine(completion.Content[0].Text);
    break;
}
Important: The JSON argument parsing above is intentionally simplified for demonstration. Production applications should deserialize tool arguments using System.Text.Json, validate all inputs, and handle malformed requests safely.

Production-Ready Argument Parsing

Instead of manually parsing JSON strings, use System.Text.Json.

using System.Text.Json;

public class OrderRequest
{
    public int OrderId { get; set; }
}

OrderRequest request =
    JsonSerializer.Deserialize<OrderRequest>(
        toolCall.FunctionArguments.ToString()
    )!;

Then execute:

string result =
    orderService.GetOrderStatus(request.OrderId);

This is safer and easier to maintain.


What Makes This an AI Agent?

You might ask:

"Isn't this just function calling?"

Function calling is one of the building blocks.

The agent behavior comes from combining the model with a loop that can:

  • Understand the user's goal
  • Choose a tool
  • Execute the tool
  • Observe the result
  • Decide whether another action is required
  • Return the final result

In simplified form:

LLM
 ↓
Decision
 ↓
Tool
 ↓
Observation
 ↓
LLM
 ↓
Decision
 ↓
Tool
 ↓
Observation
 ↓
Final Answer

Adding Multiple Tools

An agent becomes more useful when it has multiple tools.

For example:

get_order_status()
get_customer()
check_inventory()
get_shipment()
search_knowledge_base()
send_email()

The model can select the appropriate tool based on the user's request.

For example:

User:
"Is Product 123 available?"

        ↓

Agent

        ↓

check_inventory(123)

Another request might result in:

User:
"Where is my order?"

        ↓

Agent

        ↓

get_order_status(1001)

Tool Dispatcher Pattern

When you have many tools, it is useful to create a central dispatcher.

switch (toolCall.FunctionName)
{
    case "get_order_status":
        return GetOrderStatus(toolCall);

    case "get_customer":
        return GetCustomer(toolCall);

    case "check_inventory":
        return CheckInventory(toolCall);

    default:
        throw new InvalidOperationException(
            $"Unknown tool: {toolCall.FunctionName}");
}

This keeps the agent loop separate from the business logic.


Recommended .NET Architecture

For a production application, avoid putting everything inside Program.cs.

A cleaner structure could be:

SimpleAiAgent/
│
├── Agents/
│   ├── AiAgent.cs
│   └── AgentOptions.cs
│
├── Tools/
│   ├── IAgentTool.cs
│   ├── OrderTool.cs
│   ├── CustomerTool.cs
│   └── InventoryTool.cs
│
├── Services/
│   ├── OrderService.cs
│   └── CustomerService.cs
│
├── Models/
│   ├── Order.cs
│   └── Customer.cs
│
├── Program.cs
└── appsettings.json

This separation makes the application easier to test and maintain.


Adding an Interface for Tools

You can define a common interface:

public interface IAgentTool
{
    string Name { get; }

    string Description { get; }

    Task<string> ExecuteAsync(
        string arguments);
}

Each tool can implement this interface.

public class OrderTool : IAgentTool
{
    public string Name => "get_order_status";

    public string Description =>
        "Gets the current status of a customer order.";

    public Task<string> ExecuteAsync(string arguments)
    {
        // Validate arguments
        // Call order service
        // Return result

        return Task.FromResult(
            "Order is shipped."
        );
    }
}

Adding RAG to the Agent

We can extend the agent by adding a RAG tool.

search_company_documents()

Now the agent can answer questions using company documentation.

User
 ↓
Agent
 ↓
LLM
 ↓
Need company information?
 ↓
RAG Tool
 ↓
Vector Database
 ↓
Relevant Documents
 ↓
LLM
 ↓
Answer

This is a powerful combination of AI agents and RAG.


Adding MCP

MCP can also be incorporated into an agent architecture.

AI Agent
    ↓
MCP Client
    ↓
MCP Server
    ↓
Tools
    ↓
External Systems

Instead of implementing every integration directly inside the agent application, MCP can provide a standardized way for compatible AI applications to discover and use external capabilities.


Adding Memory

An agent can also maintain conversation or task state.

Conversation

User:
"My order is 1001."

Agent:
"Order 1001 is shipped."

User:
"When will it arrive?"

Agent:
"Order 1001 is expected tomorrow."

The agent needs the previous context to understand what the user means by it.

For longer-lived applications, memory can be stored in databases or other persistent storage systems.


Adding Guardrails

Production agents should not be allowed to execute arbitrary operations without controls.

Consider a tool such as:

delete_customer()
refund_payment()
cancel_order()

These operations can have real business consequences.

Therefore, implement:

  • Authentication
  • Authorization
  • Input validation
  • Tool allowlists
  • Rate limiting
  • Timeouts
  • Maximum agent steps
  • Audit logging
  • Human approval for sensitive operations

Maximum Agent Steps

An agent should not be allowed to loop forever.

For example:

const int maxSteps = 10;

for (int step = 0; step < maxSteps; step++)
{
    // Ask LLM
    // Execute tools
    // Continue or finish
}

If the maximum number of steps is reached, stop the agent and return an appropriate message.


Error Handling

Tools can fail.

For example:

Database unavailable
API timeout
Invalid order ID
Authorization failure
Network failure

Your tool layer should handle these errors gracefully.

try
{
    var result = await orderService.GetOrderStatusAsync(orderId);

    return result;
}
catch (Exception ex)
{
    // Log exception
    // Return safe tool result
}

The agent can then decide whether it should retry, use another tool, or report the problem.


Logging an AI Agent

Agent applications should have detailed logging.

Useful information includes:

  • User request
  • Agent execution ID
  • Tool selected
  • Tool arguments
  • Tool execution time
  • Tool result status
  • LLM response time
  • Number of agent steps
  • Errors

Be careful not to log sensitive information such as passwords, API keys, payment information, or unnecessary personal data.


Simple Agent Architecture for .NET

                   User
                     ↓
                ASP.NET Core
                     ↓
                 AI Agent
                     ↓
                    LLM
                     ↓
              Tool Dispatcher
                     ↓
        ┌────────────┼────────────┐
        ↓            ↓            ↓
     Order API    Database      RAG
        ↓            ↓            ↓
      Data         Data       Documents
        └────────────┼────────────┘
                     ↓
                 Tool Result
                     ↓
                    LLM
                     ↓
                 Final Answer

Agent vs Normal API

It is important to understand when an agent is actually necessary.

If your application simply needs:

GET /orders/1001

you probably do not need an AI agent.

A normal API is simpler and more predictable.

An agent becomes more useful when the request is open-ended:

"Investigate why order 1001 is delayed
and tell me what action we should take."

The agent may need to combine several operations:

Get Order
   ↓
Check Payment
   ↓
Check Shipment
   ↓
Search Documentation
   ↓
Analyze
   ↓
Recommend Action

Common Mistakes When Building AI Agents

1. Giving the Agent Too Many Tools

Providing hundreds of tools can make tool selection more difficult and increase complexity.

2. Poor Tool Descriptions

Tool descriptions should clearly explain what the tool does and when it should be used.

3. No Validation

Never trust tool arguments simply because they came from an LLM.

4. No Step Limit

Always protect the application from endless agent loops.

5. No Authorization

Agents should operate with only the permissions they actually need.

6. Using an Agent for Everything

Simple deterministic operations are often better implemented using normal application logic.


Agentic Application Design Principle

A useful principle is:

Use AI for decisions that benefit from flexibility, and use deterministic code for operations that require predictability.

For example:

AI:
"What should I do next?"

Code:
"How do I execute this operation safely?"

The AI can select the tool, while your application remains responsible for validation, security, business rules, and actual execution.


Complete Flow

Our simple AI agent can now be represented as:

                User
                  ↓
          "Check order 1001"
                  ↓
              AI Agent
                  ↓
                 LLM
                  ↓
          Choose Tool
                  ↓
        get_order_status()
                  ↓
          Validate Input
                  ↓
          Execute C# Code
                  ↓
          Order Service
                  ↓
          Business System
                  ↓
            Tool Result
                  ↓
                 LLM
                  ↓
            Final Answer

Key Takeaways

  • An AI agent can be built using an LLM, tools, application logic, and an execution loop.
  • Function calling is an important building block for tool-based agents.
  • The LLM decides which tool may be useful, but the application executes the tool.
  • Tool arguments must be validated before execution.
  • Multiple tools allow agents to perform more complex tasks.
  • RAG can provide an agent with access to external knowledge.
  • MCP can provide a standardized way to connect compatible AI applications with external capabilities.
  • Memory can maintain useful conversation or task state.
  • Production agents need security, authorization, logging, error handling, and step limits.
  • Not every application needs an AI agent.
  • Deterministic code should continue to handle critical business rules and operations.

Conclusion

Building an AI agent does not require a huge framework to understand the fundamentals.

At its core, an agent can be thought of as:

Goal
 ↓
LLM
 ↓
Choose Tool
 ↓
Execute Tool
 ↓
Observe Result
 ↓
LLM
 ↓
Next Action
 ↓
Repeat
 ↓
Final Answer

With C# and .NET 8, you can build this architecture using familiar concepts such as classes, interfaces, dependency injection, APIs, services, logging, and asynchronous programming.

Once the basic agent works, you can gradually add RAG, MCP, memory, additional tools, authentication, observability, and human approval.

The important thing is to start with a small, well-defined agent and expand its capabilities only when the use case requires them.

Next: AI Agent Memory Explained: Short-Term vs Long-Term Memory — Learn how AI agents maintain conversation context, task state, and persistent knowledge.

Tuesday, September 8, 2026

LLM vs AI Agent vs Chatbot: What’s the Difference?

Artificial Intelligence has introduced many terms that sound similar: LLM, chatbot, AI assistant, and AI agent.

These terms are often used interchangeably, but they describe different concepts.

An LLM can generate text. A chatbot provides a conversational interface. An AI assistant can help users perform tasks, while an AI agent can use tools and make decisions to accomplish a goal.

Understanding these differences is important when designing modern AI applications.


LLM vs Chatbot vs AI Agent — The Simple Explanation

LLM
↓
The AI model that understands and generates content.

Chatbot
↓
An application that allows users to interact conversationally.

AI Assistant
↓
A helpful AI application that can use context and tools
to assist with tasks.

AI Agent
↓
A goal-oriented system that can decide actions,
use tools, observe results, and continue working.

These concepts can overlap. For example, an AI agent can use an LLM and can also provide a chatbot-like interface.


What Is an LLM?

LLM stands for Large Language Model.

An LLM is an AI model trained on large amounts of text and other data to understand and generate language.

Examples of tasks an LLM can perform include:

  • Answering questions
  • Summarizing text
  • Generating code
  • Translating languages
  • Explaining technical concepts
  • Generating structured output
  • Analyzing information provided in its context

A simple interaction looks like:

User Prompt
     ↓
    LLM
     ↓
Generated Response

The LLM itself is the model. It is not necessarily a complete application.


Example of an LLM

Suppose a developer asks:

"Explain dependency injection in .NET."

The LLM can generate an explanation:

Dependency Injection is a design pattern
where dependencies are provided to a class
rather than created directly by the class.

This is a simple model interaction.


What Is a Chatbot?

A chatbot is an application that provides a conversational interface.

A chatbot may use an LLM, but the chatbot itself is the complete application around the model.

User
 ↓
Chat Interface
 ↓
Application
 ↓
LLM
 ↓
Response
 ↓
Chat Interface
 ↓
User

The chatbot can manage conversations, authentication, conversation history, UI, safety rules, and other application functionality.


Does a Chatbot Always Use an LLM?

No.

Traditional chatbots existed long before modern LLMs.

A traditional rule-based chatbot might work like:

User:
"What are your opening hours?"

        ↓

Rule:
If message contains "opening hours"

        ↓

Return:
"We are open from 9 AM to 6 PM."

An LLM-powered chatbot is more flexible because it can understand natural language rather than relying only on predefined rules.


What Is an AI Assistant?

An AI assistant is an application designed to help a user perform tasks or obtain information.

An assistant can combine:

  • LLMs
  • Conversation history
  • Tools
  • APIs
  • RAG
  • Memory
  • Application-specific instructions

For example, an AI assistant for a company might:

Answer questions
Search company documents
Check order status
Search customer information
Create reports
Summarize emails

An assistant does not necessarily need to be fully autonomous.


What Is an AI Agent?

An AI agent is a goal-oriented system that uses an AI model to decide what actions to take and interact with external tools or systems to accomplish a task.

A simplified architecture is:

User Goal
    ↓
   LLM
    ↓
Choose Action
    ↓
Use Tool
    ↓
Observe Result
    ↓
   LLM
    ↓
Choose Next Action
    ↓
Repeat
    ↓
Final Result

The key difference is the action loop.


A Simple AI Agent Example

Imagine a user says:

"Find out why order 12345 is delayed
and tell me what I should do."

An agent might perform:

1. Find Order 12345
       ↓
2. Check Order Status
       ↓
3. Check Shipment Status
       ↓
4. Find Delivery Information
       ↓
5. Analyze the results
       ↓
6. Generate recommendation

The agent can determine which actions are needed based on the results it receives.


LLM vs Chatbot vs AI Agent

Feature LLM Chatbot AI Agent
What is it? AI model Conversational application Goal-oriented AI system
Main purpose Generate and understand content Conversation Complete tasks
Conversation Can support it Yes Usually yes
Uses tools Not inherently Optional Commonly
Can make multi-step decisions Limited by itself Usually limited Yes
Memory Requires context/application Can maintain conversation history Can use short and long-term memory
External systems Requires integration Can integrate Commonly integrates through tools
Goal-oriented Not necessarily Usually conversational Yes

How an LLM Fits Inside an AI Agent

An AI agent does not replace the LLM.

The LLM is usually one of the most important components of the agent.

                 AI Agent
                     │
          ┌──────────┼──────────┐
          ↓          ↓          ↓
         LLM       Memory      Tools
          │                     │
          │                     ↓
          │              External Systems
          │
          ↓
       Decision
          ↓
       Action

The LLM can interpret the goal and help determine which action should happen next.


What Are Tools?

A tool is an operation that an AI application or agent can invoke.

Examples include:

search_web()
get_customer()
get_order()
check_inventory()
query_database()
send_email()
create_ticket()
calculate()

Tools allow AI systems to interact with the real world or with business applications.


Function Calling and AI Agents

Function calling allows an LLM to request that a specific function or tool be executed.

For example:

User:
"What's the stock for product 100?"

        ↓

LLM

        ↓

Tool Call:
check_inventory(100)

        ↓

Application

        ↓

Inventory System

        ↓

Result:
Stock = 12

        ↓

LLM

        ↓

"Product 100 currently has 12 items in stock."

This is one of the mechanisms that enables an AI agent to interact with external systems.


Where Does RAG Fit?

RAG stands for Retrieval-Augmented Generation.

RAG allows an AI application to retrieve relevant information from an external knowledge source and provide it to the LLM.

User Question
      ↓
   Retrieval
      ↓
Vector Database
      ↓
Relevant Documents
      ↓
     LLM
      ↓
    Answer

RAG is useful when the AI needs information that may not be available in the model's training data or when answers need to be grounded in a specific knowledge base.


RAG in an AI Agent

RAG can also be exposed as a tool.

AI Agent
    ↓
Search Knowledge Tool
    ↓
RAG
    ↓
Vector Database
    ↓
Relevant Documents
    ↓
AI Agent

The agent can decide when it needs to search the knowledge base.


Where Does MCP Fit?

MCP stands for Model Context Protocol.

MCP provides a standardized protocol for compatible AI applications to interact with external capabilities such as tools and resources.

A simplified architecture is:

AI Application
      ↓
   MCP Client
      ↓
   MCP Server
      ↓
 ┌────┼──────────┐
 ↓    ↓          ↓
Tools Resources Prompts

MCP can therefore be part of an AI agent architecture.

AI Agent
    ↓
MCP Client
    ↓
MCP Server
    ↓
External Tools
    ↓
APIs / Databases / Files

AI Assistant vs AI Agent

The terms assistant and agent can overlap, and there is no single universally accepted boundary between them.

Generally, an assistant is focused on helping the user, while an agent emphasizes goal-oriented action and decision-making.

For example:

AI Assistant:

User:
"What's my order status?"

Assistant:
"Your order is being shipped."

An agent might handle a more complex request:

User:
"My order is late. Find out why and
contact support if necessary."

Agent:

Find Order
   ↓
Check Shipment
   ↓
Identify Problem
   ↓
Determine Action
   ↓
Contact Support
   ↓
Report Result

Simple Example: Restaurant Reservation

Consider a user asking:

"Find a restaurant for four people
tomorrow at 7 PM and make a reservation."

An LLM can understand the request.

A chatbot can provide a conversational interface.

An assistant can help search for restaurants.

An agent could potentially:

Understand Request
       ↓
Find Restaurants
       ↓
Check Availability
       ↓
Compare Options
       ↓
Select Based on Criteria
       ↓
Make Reservation
       ↓
Confirm Reservation

The agent is coordinating multiple actions to achieve a goal.


Simple Example: Software Development

Imagine a developer says:

"Find the cause of this error
and fix the code."

An LLM can analyze the error.

A chatbot can discuss the problem.

An AI assistant can suggest code.

An AI coding agent may be able to:

Read Source Code
      ↓
Search Related Files
      ↓
Inspect Configuration
      ↓
Analyze Error
      ↓
Modify Code
      ↓
Run Tests
      ↓
Inspect Test Results
      ↓
Fix Problems
      ↓
Run Tests Again

This demonstrates why agents are becoming important in software development.


Reactive vs Agentic Systems

A simple LLM application is often reactive:

Input
 ↓
Process
 ↓
Output

An agentic system can be iterative:

Goal
 ↓
Think / Decide
 ↓
Act
 ↓
Observe
 ↓
Think / Decide
 ↓
Act
 ↓
Observe
 ↓
Complete Goal

The ability to iterate based on observations is a key characteristic of agentic systems.


Does an AI Agent Have to Be Autonomous?

No.

An agent can operate with different levels of autonomy.

For example:

Level 1:
AI suggests an action.

Level 2:
AI prepares the action and asks for approval.

Level 3:
AI executes low-risk actions automatically.

Level 4:
AI performs multi-step tasks with limited supervision.

The appropriate level depends on the application's risk, security requirements, and business rules.


Human-in-the-Loop AI Agents

For sensitive operations, a human can remain in control.

AI Agent
   ↓
Prepare Action
   ↓
Human Approval
   ↓
Execute Tool
   ↓
Result

For example, an AI agent might prepare a refund but require a human to approve it before the transaction is executed.


AI Agent Architecture

A modern AI application may combine many of the concepts we have discussed:

                         User
                           ↓
                    Chat Interface
                           ↓
                       AI Agent
                           ↓
                          LLM
                           ↓
                  Decision / Planning
                           ↓
             ┌─────────────┼─────────────┐
             ↓             ↓             ↓
           Tools          RAG           MCP
             ↓             ↓             ↓
            APIs       Vector DB    External Systems
             ↓             ↓             ↓
             └─────────────┼─────────────┘
                           ↓
                       Observation
                           ↓
                          LLM
                           ↓
                    Next Action?
                      ↙       ↘
                    Yes        No
                     ↓          ↓
                   Tools      Answer

How Everything Fits Together

The relationship between these technologies can be summarized like this:

LLM
 │
 │ provides intelligence
 ↓
AI Application
 │
 ├── Chatbot Interface
 │
 ├── Assistant Capabilities
 │
 ├── RAG
 │
 ├── Function Calling
 │
 └── MCP
        │
        ↓
      Tools
        │
        ↓
 APIs / Databases / Files / Services

An AI agent is an application architecture that can use these capabilities to accomplish goals.


Which One Should You Build?

The answer depends on the problem.

Use an LLM when:

  • You need text generation.
  • You need summarization.
  • You need classification or extraction.
  • You need natural-language understanding.

Use a Chatbot when:

  • You need a conversational interface.
  • Users primarily ask questions.
  • The application does not need complex autonomous actions.

Use an AI Assistant when:

  • You want AI to help users perform tasks.
  • You need context and useful tools.
  • The user remains actively involved.

Use an AI Agent when:

  • The task involves multiple steps.
  • The next action depends on previous results.
  • The system needs to select between tools.
  • The user provides a goal rather than a detailed procedure.

Comparison Using a Real Example

Suppose the user says:

"Analyze our sales data and tell me
why this month's revenue decreased."

LLM:

Can analyze sales data if the data is provided in its context.

Chatbot:

Can provide a conversational interface for asking questions about the data.

AI Assistant:

Can help retrieve and analyze the relevant data.

AI Agent:

Get Sales Data
      ↓
Calculate Revenue
      ↓
Compare Previous Month
      ↓
Analyze Product Categories
      ↓
Identify Changes
      ↓
Generate Explanation

The agent can coordinate the entire process.


Important: AI Agent Does Not Mean Human-Level Intelligence

The word agent can sometimes make AI systems sound more capable than they actually are.

An AI agent is still software operating within the capabilities and constraints defined by its architecture.

It may:

  • Choose an incorrect tool.
  • Misinterpret information.
  • Generate an incorrect plan.
  • Produce an incorrect answer.
  • Fail to complete a task.

Therefore, production agents need appropriate validation, permissions, monitoring, logging, and error handling.


Key Takeaways

  • LLM means Large Language Model.
  • An LLM is the model that understands and generates content.
  • A chatbot is an application that provides a conversational interface.
  • An AI assistant helps users accomplish tasks using AI and potentially external capabilities.
  • An AI agent is a goal-oriented system that can decide actions and use tools to accomplish tasks.
  • Function calling allows AI models to request tool execution.
  • RAG provides access to external knowledge.
  • MCP provides a standardized protocol for compatible AI applications to interact with external capabilities.
  • AI agents can combine LLMs, tools, RAG, memory, APIs, and MCP.
  • Not every AI application needs an agent.
  • Deterministic workflows are often better for predictable business processes.

Conclusion

The easiest way to remember the difference is:

LLM
↓
The model.

Chatbot
↓
The conversational application.

AI Assistant
↓
The application that helps the user.

AI Agent
↓
The goal-oriented system that can decide,
use tools, observe results, and continue working.

These concepts are not mutually exclusive. A modern AI application can contain an LLM inside an AI agent, provide a chatbot interface, use RAG for knowledge, use function calling for tools, and use MCP to connect to external capabilities.

Understanding this architecture is an important foundation for building production-ready AI applications.

Next: How AI Agents Use Tools: Function Calling Explained with C# — Learn how an LLM can select and invoke C# functions to interact with APIs, databases, and external systems.

Monday, September 7, 2026

What Is an AI Agent? A Beginner’s Guide to AI Agents

We have already explored LLMs, RAG, embeddings, vector databases, function calling, and MCP.

The next step is to understand one of the most important concepts in modern AI: AI Agents.

An AI chatbot usually responds to a question. An AI agent can go further: it can decide what actions are needed, use tools, observe the results, and continue working toward a goal.

In this beginner-friendly guide, we will understand what an AI agent is, how it works, the agent loop, tools, memory, planning, reasoning, observations, and how AI agents differ from traditional chatbots and LLM applications.


What Is an AI Agent?

An AI Agent is a software system that uses an AI model to pursue a goal by deciding what actions to take and interacting with external tools or systems.

A simplified definition is:

AI Agent =
LLM + Instructions + Tools + State/Memory + Action Loop

Unlike a simple chatbot, an agent can perform multiple steps to accomplish a task.


Simple Example

Imagine asking an AI assistant:

"Find the cheapest flight to Chennai,
check the weather there, and prepare a travel summary."

A simple chatbot may provide general information.

An AI agent could potentially:

Understand the goal
      ↓
Search flights
      ↓
Compare prices
      ↓
Check Chennai weather
      ↓
Collect results
      ↓
Prepare summary
      ↓
Return answer

The important part is that the system performs a sequence of actions instead of generating only one response.


Chatbot vs AI Agent

A traditional chatbot often follows this pattern:

User
 ↓
LLM
 ↓
Answer

An agent can follow a more complex loop:

User Goal
    ↓
   LLM
    ↓
Choose Action
    ↓
Use Tool
    ↓
Observe Result
    ↓
   LLM
    ↓
Choose Next Action
    ↓
Use Tool
    ↓
Observe Result
    ↓
Final Answer

This ability to repeatedly interact with tools is one of the defining characteristics of agentic systems.


The AI Agent Loop

The most important concept to understand is the agent loop.

              ┌───────────────┐
              │   User Goal   │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │      LLM      │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │ Decide Action │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │     Tool      │
              └───────┬───────┘
                      ↓
              ┌───────────────┐
              │   Observation │
              └───────┬───────┘
                      ↓
                    LLM
                      ↓
                Next Action?
                 ↙       ↘
               Yes        No
                ↓          ↓
              Tool       Answer

The agent continues this cycle until it determines that the task is complete or it reaches a configured limit.


Why Do AI Agents Need Tools?

An LLM has limitations.

For example, a model may not automatically be able to:

  • Query your company's database
  • Read a private file
  • Check your inventory system
  • Call an internal API
  • Send an email
  • Execute a business operation

Tools provide the connection between the AI model and external systems.

                    AI Agent
                        ↓
                       LLM
                        ↓
              ┌─────────┼─────────┐
              ↓         ↓         ↓
           Search      API     Database
            Tool       Tool       Tool
              ↓         ↓         ↓
           Search     Service   Database

What Is an Agent Tool?

A tool is an operation that an AI agent can invoke to accomplish part of a task.

For example:

get_customer()
search_orders()
check_inventory()
search_documents()
send_email()
calculate_total()

A tool generally has:

  • A name
  • A description
  • Input parameters
  • An implementation
  • An output

Simple Tool Example in C#

Suppose we have a C# method:

public string GetCustomer(int customerId)
{
    return $"Customer {customerId} information";
}

An AI agent could have access to this operation as a tool.

The model might decide:

Tool:
GetCustomer

Arguments:
customerId = 10025

The application executes the C# method and sends the result back to the model.


What Is Planning?

An agent often needs to determine what steps should be performed to accomplish a goal.

For example:

Goal:
"Prepare a report about today's sales."

Possible plan:

1. Get today's sales.
2. Calculate total revenue.
3. Find the top-selling products.
4. Compare with yesterday.
5. Generate a summary.

The agent can then execute these operations using available tools.


Planning Does Not Always Mean a Fixed Plan

Agents can also plan dynamically.

For example:

Goal
 ↓
Search sales
 ↓
Result indicates missing data
 ↓
Search another source
 ↓
Analyze data
 ↓
Generate report

The next action can depend on the result of the previous action.

This makes agents different from simple predefined workflows.


What Is Observation?

After an agent executes a tool, it receives an observation or result.

For example:

Agent Action:

check_inventory("PRODUCT-100")

        ↓

Tool Result:

{
    "product": "PRODUCT-100",
    "stock": 5
}

The agent then uses that information to decide what to do next.

Action
  ↓
Tool
  ↓
Observation
  ↓
LLM
  ↓
Next Action

What Is Agent Memory?

Memory allows an agent to maintain useful information across interactions or during a task.

There are several ways to think about memory.

Short-Term Memory

Short-term memory contains information from the current conversation or task.

User:
My order number is 12345.

Later:

What is the status of my order?

The agent can use the conversation context to understand that the order number is 12345.

Long-Term Memory

Long-term memory can store information that should remain available beyond a single interaction.

For example:

User preferences
Previous interactions
Saved information
Business knowledge

Long-term memory can be implemented using databases, vector stores, or other persistent storage mechanisms depending on the use case.


RAG as Agent Memory or Knowledge

RAG can provide an agent with access to external knowledge.

AI Agent
    ↓
Search Knowledge Tool
    ↓
RAG
    ↓
Vector Database
    ↓
Relevant Documents
    ↓
Agent

This allows the agent to retrieve information when it needs it instead of keeping the entire knowledge base inside the prompt.


AI Agent vs LLM

LLM AI Agent
Generates text or structured output Uses an LLM to pursue a goal
Usually responds to a prompt Can perform multiple actions
Does not inherently execute external operations Can use tools
Usually stateless unless context is provided Can maintain state or memory
One model interaction can be enough May require multiple model/tool interactions

AI Agent vs Chatbot

Chatbot AI Agent
Primarily conversational Goal-oriented
Usually answers questions Can perform actions
May use an LLM only Can use multiple tools
Usually follows request → response Can execute multiple steps
Limited external interaction Can interact with external systems

AI Agent vs Traditional Automation

Traditional automation usually follows a predefined sequence.

Step 1
  ↓
Step 2
  ↓
Step 3
  ↓
Step 4

An AI agent can dynamically choose the next action.

Goal
 ↓
LLM
 ↓
Choose Action
 ↓
Result
 ↓
LLM
 ↓
Choose Next Action
 ↓
Result
 ↓
Done

However, not every problem needs an AI agent.

If the workflow is completely deterministic, traditional automation may be simpler, cheaper, faster, and easier to test.


When Should You Use an AI Agent?

AI agents are particularly useful when:

  • The task requires multiple steps.
  • The next step depends on the previous result.
  • The system needs to choose between multiple tools.
  • The task requires interaction with external systems.
  • The exact workflow cannot be completely predefined.
  • The user provides a high-level goal rather than detailed instructions.

When Should You NOT Use an AI Agent?

Agents are not always the best solution.

For a simple operation such as:

GetCustomerById(10025)

you probably do not need an AI agent.

A normal API call is faster and more predictable.

Similarly, a deterministic workflow such as:

Receive Order
    ↓
Validate Payment
    ↓
Update Database
    ↓
Send Confirmation

may be better implemented using normal application logic or workflow automation.


Agent Example: Customer Support

Imagine a customer says:

"My order hasn't arrived. Please check what happened."

An AI agent could perform:

Understand Customer Request
          ↓
Identify Customer
          ↓
Find Order
          ↓
Check Order Status
          ↓
Check Shipment
          ↓
Analyze Result
          ↓
Generate Response

The agent might need multiple tools:

get_customer()
get_orders()
get_order_status()
get_shipment()

The exact sequence can depend on the information returned from each tool.


Agent Example: Software Developer Assistant

A developer might ask:

"Find why the payment service is failing
and suggest a fix."

An AI coding agent could potentially:

Search Source Code
      ↓
Search Logs
      ↓
Inspect Configuration
      ↓
Find Related Code
      ↓
Analyze Error
      ↓
Suggest Fix

Depending on its permissions and tools, an agent might also run tests or inspect a repository.

Every additional capability should be protected with appropriate permissions.


Agent Example: Data Analysis

User:

"Analyze this month's sales and
tell me why revenue decreased."

The agent could:

Get Sales Data
      ↓
Calculate Revenue
      ↓
Compare Previous Month
      ↓
Analyze Product Categories
      ↓
Identify Changes
      ↓
Generate Explanation

This is a goal-oriented workflow rather than a simple question-answer interaction.


What Is Tool Selection?

An agent may have multiple tools available.

Tools:

search_customer
get_order
check_inventory
search_documents
send_email
calculate

If the user asks:

"Do we have Product 123 in stock?"

The agent should select:

check_inventory("Product 123")

Tool selection is typically guided by the model's understanding of the task and the available tool descriptions.


Agent State

An agent may need to maintain state while performing a task.

For example:

Task State

CustomerId = 10025
OrderId = 12345
OrderStatus = "Delayed"
ShipmentId = "SHIP-456"

State can be maintained in application memory, a database, a workflow engine, or another appropriate storage mechanism.


Agent Loop Example

Consider this request:

"Check Product 123 and order it if
there are fewer than 5 items in stock."

The agent could reason through the task as:

Goal
 ↓
Check Inventory
 ↓
Result: 3 items
 ↓
Condition is true
 ↓
Create Order
 ↓
Order Result
 ↓
Final Answer

The important part is that the second action depends on the first tool result.


Agent Guardrails

AI agents can make decisions and execute actions, so guardrails are important.

Examples include:

  • Tool allowlists
  • Input validation
  • Authorization
  • Rate limits
  • Maximum number of steps
  • Timeouts
  • Human approval
  • Audit logging

For example, a read operation might execute automatically:

get_customer()
get_order()
search_documents()

But a high-impact operation might require approval:

delete_customer()
refund_payment()
send_large_payment()

The exact approval policy should depend on the application's risk level.


Human-in-the-Loop

Some agent workflows should involve a human before performing important actions.

AI Agent
   ↓
Prepare Action
   ↓
Human Approval
   ↓
Execute Tool
   ↓
Result

For example:

AI:
"I found an invoice for ₹50,000.
Do you want me to approve it?"

        ↓

Human:
"Yes"

        ↓

Agent:
Execute approval

This approach can significantly reduce the risk of unintended actions in sensitive workflows.


How MCP Fits Into AI Agents

MCP can provide a standardized way for compatible AI applications to interact with external capabilities.

An agent can use MCP servers to access tools and resources.

AI Agent
    ↓
MCP Client
    ↓
MCP Server
    ↓
 ┌─────────────┬─────────────┐
 ↓             ↓             ↓
Tools       Resources      Prompts
 ↓             ↓             ↓
APIs        Documents     Templates

This makes MCP particularly relevant to agent-based architectures.


How RAG Fits Into AI Agents

RAG can provide an agent with access to external knowledge.

AI Agent
    ↓
Search Tool
    ↓
RAG Pipeline
    ↓
Vector Search
    ↓
Relevant Context
    ↓
LLM

For example, a support agent could search company documentation before answering a customer question.


AI Agent Architecture

A more complete agent architecture might look like this:

                    User Goal
                        ↓
                 ┌─────────────┐
                 │ AI Agent    │
                 └──────┬──────┘
                        ↓
                      LLM
                        ↓
                Planning / Decision
                        ↓
               ┌────────┼────────┐
               ↓        ↓        ↓
             Tool     RAG      MCP
               ↓        ↓        ↓
              API    Vector   External
                     Search    Systems
               └────────┼────────┘
                        ↓
                    Observation
                        ↓
                       LLM
                        ↓
                 More Actions?
                   ↙       ↘
                 Yes        No
                  ↓          ↓
                Tools      Answer

Single-Agent vs Multi-Agent Systems

A single-agent system uses one agent to perform the task.

User
 ↓
Agent
 ↓
Tools
 ↓
Answer

A multi-agent system uses multiple specialized agents.

                 Main Agent
                     ↓
          ┌──────────┼──────────┐
          ↓          ↓          ↓
      Research     Coding     Testing
       Agent       Agent       Agent
          ↓          ↓          ↓
       Sources     Code       Tests

Multi-agent architectures can be useful for complex workflows, but they also introduce additional complexity and should not be used when a simpler architecture is sufficient.


AI Agent vs Workflow

Workflow AI Agent
Steps are usually predefined Steps can be selected dynamically
Highly deterministic More adaptive
Easy to predict May produce different execution paths
Usually easier to test Requires additional evaluation and controls
Good for stable business processes Good for open-ended or dynamic tasks

In practice, many systems combine both approaches.

Deterministic Workflow
        ↓
      AI Agent
        ↓
Dynamic Decision
        ↓
Deterministic Tool
        ↓
Business System

Common AI Agent Terminology

Term Meaning
AI Agent Goal-oriented system that uses AI to decide and perform actions
Agent Loop Repeated cycle of deciding, acting, observing, and deciding again
Tool Operation an agent can invoke
Observation Result returned after an action
Planning Determining steps needed to accomplish a goal
Memory Information retained during or across tasks
State Current information maintained by the agent
Guardrail Control that limits or validates agent behavior
Human-in-the-Loop Human approval or intervention during an agent workflow

Key Takeaways

  • An AI Agent is a goal-oriented AI system that can decide and perform actions.
  • An LLM is the reasoning and generation component, but an agent typically includes additional components.
  • Tools allow agents to interact with external systems.
  • The agent loop commonly consists of decision, action, observation, and another decision.
  • Agents can use APIs, databases, RAG systems, MCP servers, and other tools.
  • Memory and state allow agents to maintain useful information.
  • Agents are useful for multi-step and dynamic tasks.
  • Traditional workflows are often better for deterministic processes.
  • High-impact actions should use appropriate authorization, validation, and possibly human approval.
  • RAG and MCP can be combined with AI agents.

Conclusion

An AI agent is more than an LLM that answers questions.

The key difference is the ability to work toward a goal by selecting actions, using tools, observing results, and continuing until the task is completed.

The basic agent loop can be remembered as:

Goal
 ↓
LLM
 ↓
Choose Action
 ↓
Tool
 ↓
Observation
 ↓
LLM
 ↓
Choose Next Action
 ↓
Repeat
 ↓
Final Answer

Once you understand this loop, concepts such as tool calling, MCP, RAG, memory, planning, and multi-agent systems become much easier to understand.

For developers, this is where AI moves from a simple question-and-answer system toward an application that can actually perform tasks.

Next: AI Agent vs Chatbot vs LLM: What's the Difference? — A practical comparison of LLMs, chatbots, AI assistants, and autonomous agents with real-world examples.

Sunday, September 6, 2026

MCP vs API vs Function Calling: What’s the Difference?

Modern AI applications need more than just an LLM. They often need to access databases, call APIs, search documents, execute functions, and interact with external systems.

Developers can use several approaches to connect AI models with these capabilities.

Three commonly discussed approaches are:

  • APIs
  • Function Calling / Tool Calling
  • MCP (Model Context Protocol)

Although they are related, they are not the same thing.

In this article, we will understand the differences between MCP vs API vs Function Calling, how each works, when to use them, and how they can work together in an AI application.


The Simple Explanation

The easiest way to remember the difference is:

API
↓
Allows software to communicate with another system.

Function Calling
↓
Allows an AI model to request that a function/tool be executed.

MCP
↓
Provides a standardized protocol for AI applications
to discover and interact with external capabilities.

These technologies can also be combined.


What Is an API?

API stands for Application Programming Interface.

An API provides a defined interface through which one software application can communicate with another application or service.

A typical REST API might look like:

GET /api/customers/10025

GET /api/orders/10025

POST /api/orders

A C# application can call these endpoints using HttpClient.

using HttpClient client = new HttpClient();

var response =
    await client.GetAsync(
        "https://example.com/api/customers/10025");

var result =
    await response.Content.ReadAsStringAsync();

Console.WriteLine(result);

The application knows the API endpoint and the required request format.


What Is Function Calling?

Function Calling, also commonly called Tool Calling, allows an AI model to request that an application execute a function.

For example, imagine your application has a function:

GetCustomer(int customerId)

The AI model can determine that this function is needed and request a tool call.

User:
"Show me customer 10025"

        ↓

       LLM

        ↓

Tool Call:
GetCustomer(10025)

        ↓

Application executes function

        ↓

Customer information

        ↓

       LLM

        ↓

Final Answer

The important point is that the model decides when a tool may be useful, while the application actually executes the operation.


Simple Function Calling Example

Imagine your application exposes this function:

public Customer GetCustomer(int customerId)
{
    // Query database
    // Return customer
}

The model may produce a structured tool request such as:

{
  "name": "GetCustomer",
  "arguments": {
    "customerId": 10025
  }
}

Your application receives the request and executes the corresponding C# method.


What Is MCP?

MCP stands for Model Context Protocol.

MCP is a standardized protocol designed to allow compatible AI applications to interact with external capabilities.

An MCP server can expose:

  • Tools
  • Resources
  • Prompts

A simplified architecture looks like this:

AI Application
      ↓
   MCP Client
      ↓
   MCP Server
      ↓
 ┌────┼──────────┐
 ↓    ↓          ↓
Tools Resources Prompts

The MCP server can internally communicate with APIs, databases, files, or other systems.


The Key Difference

The most important distinction is the level at which each technology operates.

Technology Main Purpose
API Software-to-software communication
Function Calling Allows an AI model to request a function/tool execution
MCP Standardizes how compatible AI applications discover and interact with external capabilities

API Example

Consider an e-commerce application.

The application has an Order API:

GET /api/orders/12345

A traditional application can call it:

var response =
    await httpClient.GetAsync(
        "/api/orders/12345");

The application knows exactly which API endpoint it needs to call.


Function Calling Example

Now imagine an AI assistant.

The user asks:

"Where is my order 12345?"

The LLM can determine that it needs order information.

LLM
 ↓
Tool Call
 ↓
get_order(12345)
 ↓
Application
 ↓
Order API
 ↓
Order Result
 ↓
LLM
 ↓
Answer

Here, function calling is the mechanism that allows the model to request the operation.


MCP Example

Now suppose the order functionality is exposed through an MCP server.

AI Application
      ↓
   MCP Client
      ↓
   MCP Server
      ↓
 get_order
      ↓
   Order API
      ↓
 Order System

The AI application can interact with the MCP server using the MCP protocol.


MCP Does Not Replace APIs

This is an important concept.

You do not necessarily need to replace your existing APIs when adopting MCP.

An MCP server can sit on top of existing services.

AI Application
      ↓
   MCP Client
      ↓
   MCP Server
      ↓
Existing REST API
      ↓
Business Application
      ↓
Database

This means your existing enterprise systems can continue to use REST APIs while an MCP layer provides AI-friendly access.


Function Calling Does Not Replace APIs Either

Function calling is usually implemented by the application that hosts the model.

For example:

LLM
 ↓
Function Call
 ↓
C# Function
 ↓
HttpClient
 ↓
REST API
 ↓
Database

The API is still responsible for communication with the backend system.


MCP vs API vs Function Calling Architecture

Here is a simplified comparison:

                 API

Application
     ↓
   HTTP
     ↓
   API
     ↓
Backend System


             Function Calling

User
 ↓
LLM
 ↓
Tool Call
 ↓
Application Function
 ↓
API / Database
 ↓
Result
 ↓
LLM


                    MCP

User
 ↓
AI Application
 ↓
MCP Client
 ↓
MCP Server
 ↓
Tool / Resource
 ↓
API / Database / Files

Who Initiates the Action?

This is another useful way to understand the difference.

Technology Who Determines the Action?
API Calling application
Function Calling LLM can request a tool call
MCP AI application can discover and use capabilities exposed by MCP servers

API Example in C#

A normal C# application might contain:

public async Task<string> GetOrderAsync(
    int orderId)
{
    var response =
        await _httpClient.GetAsync(
            $"api/orders/{orderId}");

    response.EnsureSuccessStatusCode();

    return await response.Content
        .ReadAsStringAsync();
}

The developer explicitly decides when to call the API.


Function Calling Flow in C#

With function calling, your application might expose a function definition to the model.

GetOrder

Description:
Gets order details.

Parameters:
orderId - integer

The model may respond with a tool request:

GetOrder
{
    "orderId": 12345
}

Your C# application then executes the actual method.


MCP Tool Discovery

With MCP, an MCP client can communicate with an MCP server and discover available tools.

For example:

MCP Server

Available Tools:

get_order
search_customer
search_product
check_inventory

This makes the integration more standardized than creating a separate custom integration for every AI application.


One Backend, Three Approaches

Imagine you have an inventory system.

It provides:

GET /api/products/{id}
GET /api/products/search
GET /api/inventory/{productId}

You could use the same backend in three different ways.


Approach 1: API

C# Application
      ↓
Inventory REST API
      ↓
Inventory Database

The application directly calls the API.


Approach 2: Function Calling

User
 ↓
LLM
 ↓
search_product()
 ↓
C# Application
 ↓
Inventory API
 ↓
Database

The LLM decides that the search function should be called.


Approach 3: MCP

User
 ↓
AI Application
 ↓
MCP Client
 ↓
MCP Server
 ↓
search_product
 ↓
Inventory API
 ↓
Database

The MCP server provides a standardized interface for the AI application.


Can They Be Used Together?

Yes.

In fact, they often work together in real-world AI systems.

A possible architecture is:

                    User
                      ↓
                 AI Assistant
                      ↓
                     LLM
                      ↓
                 MCP Client
                      ↓
                 MCP Server
                      ↓
                Tool Calling
                      ↓
              C# Business Logic
                      ↓
                   REST API
                      ↓
                 Database

Each layer has a different responsibility.


Example Enterprise Architecture

Consider a retail application with:

  • POS system
  • Customer service
  • Inventory system
  • Order management
  • Product catalog

The existing architecture might be:

POS
 ↓
POS API
 ↓
Database

Order Application
 ↓
Order API
 ↓
Database

Inventory Application
 ↓
Inventory API
 ↓
Database

Now an AI assistant is introduced.

Instead of rebuilding all these systems, an MCP layer can expose selected capabilities:

                    AI Assistant
                         ↓
                     MCP Client
                         ↓
                     MCP Server
               ┌─────────┼─────────┐
               ↓         ↓         ↓
          Customer     Orders   Inventory
             Tool       Tool       Tool
               ↓         ↓         ↓
          Customer     Order     Inventory
             API        API        API

This architecture allows the AI application to interact with existing business systems through standardized capabilities.


When Should You Use an API?

Use a traditional API when:

  • A normal application needs to communicate with another application.
  • You need a stable service-to-service contract.
  • You are building mobile or web applications.
  • You need external application integration.
  • You are exposing business functionality to other software.

For example:

Mobile App
   ↓
REST API
   ↓
Backend

When Should You Use Function Calling?

Function calling is useful when:

  • An LLM needs to invoke application functions.
  • You are building an AI assistant.
  • The AI needs access to a small set of application-specific tools.
  • You want the model to choose between available functions.

For example:

LLM
 ↓
get_weather()
 ↓
Application
 ↓
Weather API

When Should You Use MCP?

MCP is useful when:

  • You are building AI applications that need multiple external capabilities.
  • You want standardized AI-to-tool integrations.
  • You want tools to be discoverable by compatible MCP clients.
  • You want to reuse the same integration across compatible AI applications.
  • You need access to tools, resources, and prompts through a common protocol.

Comparison Table

Feature API Function Calling MCP
Primary purpose Software communication AI tool invocation AI capability integration
Used by Applications AI applications AI applications and compatible clients
Tool discovery Usually application-specific Tool definitions provided to the model Standardized capability discovery
Can access APIs Yes Yes Yes, through server implementations
Can perform actions Yes Yes Yes, through tools
Can provide data Yes Yes Yes, through resources and tools
Standardized for AI integrations No Depends on implementation/provider Yes

A Simple Analogy

Think about a restaurant.

An API is like the restaurant's standard ordering interface. You know what requests are available and how to place them.

Function Calling is like giving an assistant a menu and allowing the assistant to decide which item should be ordered based on what the customer asks for.

MCP is like a standardized way for assistants to discover what services are available and interact with them through a common protocol.


API vs Function Calling vs MCP in One Diagram

                 API
                  │
        Software communicates
                  │
                  ↓
             External API


           Function Calling
                  │
             LLM chooses
                  │
                  ↓
              Function
                  │
                  ↓
             Application


                  MCP
                  │
             AI Application
                  │
             MCP Client
                  │
                  ↓
             MCP Server
                  │
        ┌─────────┼─────────┐
        ↓         ↓         ↓
      Tools    Resources  Prompts

Which One Should Developers Learn?

For modern AI development, it is useful to understand all three.

They solve different problems.

Need application integration?
        ↓
       API

Need LLM to invoke application functions?
        ↓
 Function Calling

Need standardized AI access to multiple
tools, resources, or external systems?
        ↓
       MCP

In many production systems, you will use more than one of them.


How RAG Fits Into This Picture

RAG can also be combined with these technologies.

For example:

User
 ↓
AI Agent
 ↓
MCP
 ↓
RAG Tool
 ↓
Vector Database
 ↓
Relevant Documents
 ↓
LLM
 ↓
Answer

Or a RAG application could call an API to retrieve additional information.

User
 ↓
RAG Application
 ↓
Vector Search
 ↓
Relevant Documents
 ↓
API
 ↓
Additional Data
 ↓
LLM
 ↓
Answer

This shows that RAG, APIs, function calling, and MCP are not competing technologies in every scenario. They can be combined to build more capable AI systems.


Key Takeaways

  • API means Application Programming Interface.
  • APIs provide a general mechanism for software-to-software communication.
  • Function Calling allows an LLM to request that an application execute a function or tool.
  • MCP means Model Context Protocol.
  • MCP provides a standardized protocol for compatible AI applications to interact with external capabilities.
  • MCP servers can expose tools, resources, and prompts.
  • MCP can work on top of existing APIs.
  • Function calling and APIs can also be used together.
  • RAG can be exposed through tools and combined with MCP.
  • APIs, function calling, and MCP are complementary technologies rather than simple replacements for one another.

Conclusion

API, Function Calling, and MCP operate at different levels of an AI architecture.

An API provides a communication interface between software systems. Function calling allows an AI model to request that an application perform an operation. MCP provides a standardized protocol through which compatible AI applications can discover and interact with external tools, resources, and prompts.

A modern AI application might therefore look like:

                 User
                   ↓
              AI Assistant
                   ↓
                  LLM
                   ↓
              MCP Client
                   ↓
              MCP Server
                   ↓
                Tool
                   ↓
          C# Business Logic
                   ↓
                REST API
                   ↓
               Database

Understanding these layers is important before moving into the next stage of AI development: AI Agents.

Next: What Is an AI Agent? A Beginner's Guide — Learn how AI agents use LLMs, tools, memory, planning, and external systems to perform multi-step tasks.

Saturday, September 5, 2026

What Is MCP (Model Context Protocol)? A Beginner’s Guide

AI applications are becoming more powerful, but an LLM by itself has an important limitation: it cannot automatically access every external system, database, file, or application.

This is where MCP comes into the picture.

MCP stands for Model Context Protocol. It is an open protocol designed to standardize how AI applications connect models to external tools, data sources, and capabilities.

In this beginner-friendly guide, we will understand what MCP is, why it is needed, how MCP works, its architecture, MCP servers and clients, tools, resources, prompts, and how MCP fits into modern AI agents.


What Is MCP?

MCP (Model Context Protocol) is a standardized way for AI applications to interact with external systems.

Instead of building a completely different integration for every AI application, an MCP-based architecture provides a common protocol for exposing capabilities to AI clients.

A simplified view is:

AI Application
      ↓
   MCP Client
      ↓
   MCP Server
      ↓
 ┌────┼───────────┐
 ↓    ↓           ↓
Files Database   APIs

This allows an AI application to discover and use capabilities exposed by MCP servers.


Why Was MCP Needed?

Imagine you are building an AI assistant that needs access to:

  • Company documents
  • Git repositories
  • Databases
  • File systems
  • Project management systems
  • Customer information
  • External APIs

Without a standardized approach, each integration may require custom code.

AI Application
   ├── Custom Git Integration
   ├── Custom Database Integration
   ├── Custom File Integration
   ├── Custom API Integration
   └── Custom CRM Integration

As the number of integrations increases, the architecture becomes harder to maintain.

MCP provides a standardized protocol that can simplify these integrations.


MCP in Simple Terms

A simple way to think about MCP is:

MCP = A standard way for AI applications
      to discover and use external capabilities.

For example, an MCP server could expose a tool called:

search_documents

The AI application can discover that tool and invoke it when appropriate.


MCP Architecture

A basic MCP architecture contains three important components:

  • MCP Host
  • MCP Client
  • MCP Server

The relationship can be visualized as:

                 MCP Host
              AI Application
                    │
                    │
                MCP Client
                    │
                    │
              MCP Protocol
                    │
                    ↓
                MCP Server
              ┌─────┼─────┐
              ↓     ↓     ↓
            Tools Resources Prompts

What Is an MCP Host?

The MCP Host is the AI application that wants to use MCP capabilities.

Examples could include an AI-powered desktop application, IDE, or another application that supports MCP.

The host manages the overall interaction with the user and the AI model.

User
 ↓
MCP Host
 ↓
LLM
 ↓
MCP Client

What Is an MCP Client?

An MCP Client is the component responsible for communicating with an MCP server.

The client maintains the protocol connection and handles communication between the host application and the server.

MCP Host
   ↓
MCP Client
   ↓
MCP Server

A host can use MCP clients to connect to one or more MCP servers.


What Is an MCP Server?

An MCP Server exposes capabilities that an MCP client can discover and use.

For example, an MCP server could provide:

  • A file search tool
  • A database query tool
  • A Git repository tool
  • Company documentation resources
  • Custom application operations

Conceptually:

MCP Server
    │
    ├── Tool: searchFiles
    ├── Tool: getCustomer
    ├── Tool: executeQuery
    │
    ├── Resource: company-docs
    └── Prompt: support-assistant

What Are MCP Tools?

Tools represent actions that an AI application can invoke through an MCP server.

For example:

Tool:
search_customer

Input:
{
    "customerId": "12345"
}

Output:
Customer information

Another tool might be:

Tool:
search_products

Input:
{
    "query": "wireless keyboard"
}

The important concept is that the AI application can discover the available tool and its input requirements.


What Are MCP Resources?

Resources represent data or contextual information that can be made available through an MCP server.

For example:

  • Documentation
  • Files
  • Database information
  • Application configuration
  • Other contextual data

Conceptually:

MCP Server
     ↓
Resources
     ├── Documentation
     ├── Configuration
     └── Application Data

Resources are different from tools because a tool represents an operation, while a resource represents information that can be accessed as context.


What Are MCP Prompts?

Prompts allow an MCP server to expose reusable prompt templates or workflows.

For example:

Prompt:
analyze_support_ticket

Arguments:
ticketId
customerId

Purpose:
Analyze a customer support ticket
and produce a structured summary.

This can help standardize how particular tasks are performed.


MCP Tools vs Resources vs Prompts

Component Purpose Example
Tools Perform actions Search database
Resources Provide information Read documentation
Prompts Provide reusable prompt templates Analyze support ticket

How Does MCP Work?

Let's consider a simple example.

A user asks an AI assistant:

"Find the latest information about
customer 10025."

The AI determines that it needs information from an external customer system.

User Question
      ↓
      LLM
      ↓
Need Customer Information
      ↓
MCP Client
      ↓
MCP Server
      ↓
Customer Tool
      ↓
Customer System
      ↓
Result
      ↓
LLM
      ↓
Final Answer

MCP Tool Discovery

One of the important ideas in MCP is that clients can discover what capabilities an MCP server exposes.

For example, an MCP server might expose:

Available Tools

1. search_customer
2. get_customer_orders
3. search_products
4. create_support_ticket

The AI application can use the tool definitions to understand what operations are available and what inputs they require.


MCP and Function Calling

If you have worked with LLM APIs, you may already know about function calling or tool calling.

Function calling allows a model to request that an application execute a function.

For example:

LLM
 ↓
"Call get_customer"
 ↓
Application
 ↓
Customer API
 ↓
Result
 ↓
LLM

MCP is broader than simply defining a function.

It provides a standardized protocol and interaction model for exposing tools, resources, and prompts to compatible AI applications.


MCP vs Traditional API

A traditional API might expose endpoints such as:

GET /api/customers/10025
GET /api/orders/10025
POST /api/support/tickets

An MCP server could expose corresponding capabilities in a way that MCP-compatible clients can discover and interact with.

MCP Server

get_customer
get_customer_orders
create_support_ticket

The underlying implementation could still call your existing APIs.

AI Application
      ↓
MCP
      ↓
MCP Server
      ↓
Existing REST API
      ↓
Business System

This means MCP does not necessarily replace your existing APIs.


MCP Can Sit on Top of Existing Systems

This is particularly useful for enterprise applications.

Suppose your company already has:

POS API
Order API
Customer API
Inventory API
Database

An MCP server can provide AI-friendly capabilities on top of these systems.

                AI Application
                      ↓
                   MCP Client
                      ↓
                  MCP Server
                ┌─────┼─────┐
                ↓     ↓     ↓
              POS   Orders Customers
               API    API     API

The existing business systems do not necessarily need to become AI systems themselves.


MCP and AI Agents

MCP becomes particularly interesting when building AI agents.

An AI agent may need to:

  • Read files
  • Search information
  • Query databases
  • Call APIs
  • Execute business operations
  • Use multiple tools

MCP provides a standardized way for compatible AI applications to discover and use those capabilities.

                 AI Agent
                     ↓
                MCP Client
                     ↓
       ┌─────────────┼─────────────┐
       ↓             ↓             ↓
   MCP Server A  MCP Server B  MCP Server C
       ↓             ↓             ↓
     Files        Database       APIs

Example: AI Developer Assistant

Imagine building an AI assistant for software developers.

The assistant might need:

  • Git repository access
  • File search
  • Documentation search
  • Issue tracking
  • Database access

Instead of implementing every integration directly inside the AI application, MCP servers can expose these capabilities.

Developer
    ↓
AI Coding Assistant
    ↓
MCP Client
    ↓
 ┌──────────┬──────────┬───────────┐
 ↓          ↓          ↓
Git MCP   Docs MCP   Database MCP
 ↓          ↓          ↓
Git       Docs       Database

Example: AI Customer Support Agent

Consider a customer support application.

The AI agent needs to:

Search Customer
      ↓
Check Orders
      ↓
Check Product
      ↓
Create Support Ticket

An MCP server could expose these operations as tools:

search_customer
get_orders
search_product
create_ticket

The AI agent can decide which tool is appropriate based on the user's request.


MCP Request and Response

MCP communication is based on a structured protocol. MCP uses JSON-RPC 2.0 messages for protocol communication.

A simplified request can look conceptually like:

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "search_customer",
    "arguments": {
      "customerId": "10025"
    }
  }
}

The server processes the request and returns a structured result.

The exact protocol messages and capabilities depend on the MCP specification and implementation.


MCP Transport

MCP communication requires a transport mechanism between the client and server.

Depending on the deployment scenario, MCP implementations can use supported transports appropriate to local or remote communication.

For example:

Local Application
      ↓
Local MCP Server

Remote Application
      ↓
Network
      ↓
Remote MCP Server

The transport layer is separate from the higher-level MCP concepts such as tools and resources.


MCP Security

Security is extremely important when AI applications can access external systems.

Imagine an AI assistant has access to a database and a tool that can modify customer records.

You should carefully control:

  • Which tools are available
  • Which users can access them
  • What arguments are allowed
  • Which resources can be accessed
  • Authentication
  • Authorization
  • Audit logging
  • Data privacy

For example:

User
 ↓
Authentication
 ↓
Authorization
 ↓
MCP Client
 ↓
MCP Server
 ↓
Tool
 ↓
Business System

An MCP server should not automatically expose every internal operation to an AI model.


Read-Only vs Write Tools

There is an important difference between read and write operations.

A read-only tool might be:

get_customer()
search_document()
get_order()

A write operation might be:

create_order()
update_customer()
delete_file()

Write operations can have real-world consequences and should therefore be protected with appropriate authorization, validation, confirmation, and auditing.


MCP vs RAG

MCP and RAG are related to AI applications, but they solve different problems.

RAG MCP
Retrieves relevant information Standardizes connections to external capabilities
Commonly uses embeddings and vector search Can expose tools, resources, and prompts
Useful for knowledge retrieval Useful for connecting AI applications to systems
Often retrieves documents Can enable actions as well as access to information

They can also be combined.

AI Agent
   ↓
MCP
   ↓
RAG Tool
   ↓
Vector Database
   ↓
Relevant Documents
   ↓
LLM

MCP vs API

API MCP
General software integration mechanism Protocol designed for AI application context and capabilities
Usually designed around application-specific contracts Provides standardized AI-oriented interactions
Clients typically need API-specific knowledge MCP clients can discover supported capabilities
Can be used by any software Designed for compatible AI applications and servers

MCP does not make traditional APIs obsolete. In many architectures, an MCP server can actually use existing APIs behind the scenes.


MCP vs Function Calling

Function Calling MCP
Model requests a function/tool invocation Standardized protocol for AI-to-capability interaction
Often implemented inside a specific application Designed for reusable integrations
Tool definitions are usually application-specific Capabilities can be exposed through MCP servers

Why MCP Is Important for Developers

MCP can change how developers think about AI integrations.

Instead of building:

AI App
  ↓
Custom Database Code

AI App
  ↓
Custom Git Code

AI App
  ↓
Custom File Code

AI App
  ↓
Custom API Code

You can build standardized MCP servers around reusable capabilities.

                AI Applications
                 /     |      \
                /      |       \
               ↓       ↓        ↓
            MCP Client(s)
                 ↓
        Standard MCP Protocol
                 ↓
      ┌──────────┼──────────┐
      ↓          ↓          ↓
   MCP Server MCP Server MCP Server
      ↓          ↓          ↓
    Git       Database     Files

Example MCP Server for a .NET Developer

As a .NET developer, you could create an MCP server that exposes capabilities from an existing .NET application.

For example:

ASP.NET Core Application
          ↓
      Business Layer
          ↓
      MCP Server
          ↓
 ┌────────┼─────────┐
 ↓        ↓         ↓
Customers Orders  Inventory

The MCP server could expose tools such as:

get_customer
search_orders
check_inventory
search_product

An AI application that supports MCP could then discover these capabilities.


Example Enterprise Architecture

A larger enterprise architecture could look like:

                         User
                           ↓
                      AI Assistant
                           ↓
                         LLM
                           ↓
                      MCP Client
                           ↓
                   MCP Protocol
                           ↓
        ┌──────────────────┼──────────────────┐
        ↓                  ↓                  ↓
    Customer MCP       POS MCP           Docs MCP
        ↓                  ↓                  ↓
 Customer API          POS API        Vector Database
        ↓                  ↓                  ↓
     Customer            POS             Documents

This architecture separates the AI application from the implementation details of each external system.


Can MCP Replace RAG?

No.

MCP and RAG operate at different levels.

MCP can expose a RAG capability as a tool or resource.

AI Agent
   ↓
MCP Client
   ↓
RAG MCP Server
   ↓
Embedding
   ↓
Vector Search
   ↓
Documents

In this example, MCP provides the standardized connection while RAG performs information retrieval.


Can MCP Replace APIs?

Not necessarily.

Traditional APIs remain useful for application-to-application communication.

MCP can provide an AI-oriented interface on top of existing services.

AI Application
      ↓
MCP
      ↓
MCP Server
      ↓
REST API
      ↓
Existing Application

MCP and the Future of AI Applications

Modern AI applications are moving beyond simple question-and-answer interfaces.

AI systems increasingly need to:

  • Retrieve information
  • Use tools
  • Access external systems
  • Perform multi-step tasks
  • Interact with business applications

This is where protocols such as MCP become particularly useful.

LLM
 ↓
Reason
 ↓
Select Tool
 ↓
MCP
 ↓
External System
 ↓
Tool Result
 ↓
Reason Again
 ↓
Final Answer

This pattern is one of the building blocks behind modern AI agents.


Common MCP Terminology

Term Meaning
MCP Model Context Protocol
MCP Host AI application that uses MCP
MCP Client Component that communicates with an MCP server
MCP Server Server that exposes capabilities
Tool Action that can be invoked
Resource Information or contextual data
Prompt Reusable prompt template or workflow
JSON-RPC Message format used by MCP protocol communication

Key Takeaways

  • MCP stands for Model Context Protocol.
  • MCP provides a standardized way for compatible AI applications to interact with external capabilities.
  • An MCP architecture commonly involves a host, client, and server.
  • MCP servers can expose tools, resources, and prompts.
  • Tools allow AI applications to perform operations.
  • Resources provide contextual information.
  • Prompts can provide reusable prompt templates.
  • MCP can work with existing APIs and business systems.
  • MCP and RAG solve different problems and can be used together.
  • MCP is particularly useful when building AI assistants and agents that interact with external systems.
  • Security, authorization, validation, and auditing are important when exposing powerful tools.

Conclusion

MCP is an important building block for connecting AI applications to the outside world.

An LLM can generate text and reason over information, but useful AI applications often need access to documents, databases, APIs, files, and business systems.

MCP provides a standardized protocol for exposing these capabilities to compatible AI applications.

The basic architecture can be remembered as:

AI Application
      ↓
   MCP Client
      ↓
   MCP Server
      ↓
Tools / Resources / Prompts
      ↓
External Systems

Once you understand MCP, the next logical step is to understand how it compares with traditional APIs and function calling, and then see how MCP can be used to build an actual AI Agent.

Next: MCP vs APIs vs Function Calling: What's the Difference? — Learn how these three approaches differ and when a developer should use each one.