Skip to main content
VTFriday

MCP Tool Calling: The Complete Lifecycle With Claude

Updated

Source: https://www.vtfriday.com/2026/10/master-mcp-tool-calling-complete.html

In plain words:

Tool calling in the Model Context Protocol (MCP) is a 6-step request-and-response loop between an AI model and an external system. A model like Claude or a Salesforce Agentforce agent never reaches into your database on its own. Instead, it reads a catalog of approved tools, picks one that fits the user's request, fills out a structured JSON payload, and asks the host application to run it. Once the host returns the data or an error, the model reads the outcome and decides whether to stop or call another tool.

In sequence, the six stages answer six plain questions:
  1. Discover (tools/list): what tools are available in this session?
  2. Select: which tool on that list solves the user's current request?
  3. Input: what exact fields and filters does this tool expect?
  4. Call (tools/call): ask the host application to run the tool with those inputs.
  5. Result: inspect the records, confirmation ID, or error returned by the server.
  6. Reason: decide whether to answer the user now, retry after an error, or run another tool.

🗺️ Module map: Claude and enterprise MCP foundation

CLAUDE & AGENTFORCE MCP FOUNDATION
├── What Is Claude?
├── Claude Model Families & Reasoning
├── Claude Tool Use Fundamentals
├── AI Agents & Autonomous Loops
├── Model Context Protocol (MCP) Overview
├── MCP Client-Host-Server Architecture
├── MCP Security, OAuth & Governance
├── Claude + MCP + Salesforce Agentforce
├── MCP Primitives: Tools, Resources & Prompts
├── MCP Tool Calling Lifecycle <- You Are Here
└── Claudeforce & Hosted MCP Server Architecture

🎬 Worked scenario: automating sales follow-ups in Salesforce

Consider a realistic Tuesday morning for a Sales Director. She opens her AI assistant, connected to her org through a Salesforce MCP Server, and asks for help with stalled pipeline deals. This kind of request is a good example of multi-tool workflows in Claude and MCP because a single database query cannot finish the job.

Illustrative user prompt:
"Find my top three highest-value open opportunities that haven't had any activity in the last 14 days, and create a high-priority follow-up task for each one."

A plain text chatbot stalls here because the prompt requires both reading CRM records and writing new ones. With MCP wired up, the assistant and the host application split the work across several turns:

Example scenario: behind-the-scenes orchestration
  1. Claude reads the prompt and sees two distinct goals: finding stalled deals and creating follow-up tasks.
  2. Through the Salesforce MCP Server, the client has already exposed tools such as search_opportunities, run_agentforce_flow, and create_task.
  3. Claude builds a JSON request for search_opportunities, filtering by inactive_days: 14 and sorting by Amount.
  4. The MCP Client sends that call to Salesforce. Salesforce validates the user's OAuth token, enforces sharing rules, runs the query, and returns 7 matching Opportunity records.
  5. Claude inspects all 7 records, picks the 3 with the highest dollar value, and pulls their OpportunityId and OwnerId values.
  6. Claude requests create_task three times, once for each stalled deal.
  7. After Salesforce confirms all three tasks are saved, Claude writes a short summary for the Sales Director with links to the new records.
Pausing to inspect live results before deciding on the next action is what turns a single prompt into a multi-step agent loop.
Flowchart showing the six stages of the MCP tool calling lifecycle from tool discovery to reasoning

⚙️ Deep dive: the 6-step MCP tool calling lifecycle

Whether you connect Claude Desktop to a local SQLite database or wire Salesforce Agentforce to an external ERP over MCP, every tool call moves through the same six stages.

1. Tool discovery (tools/list)

When an MCP Client connects to an MCP Server, the model starts with no knowledge of what your backend can do. To populate its options, the client sends a tools/list request defined by the Model Context Protocol tools specification.

The server replies with a structured catalog of available tools. Each entry carries three pieces of metadata:

  • A unique, machine-friendly name such as search_opportunities or invoke_prompt_template.
  • A plain-English description explaining what the tool does and when to pick it.
  • A strict JSON Schema (inputSchema) listing required fields, optional parameters, and expected data types like strings, numbers, or booleans.

In Salesforce's Agentforce MCP Client setup, admins can filter which tools enter the Agentforce Asset Library using an allowlist rather than importing everything a server exposes. That matters in practice: dumping 200 tool definitions into a prompt wastes tokens and makes tool selection noisier.

2. Tool selection

Once a user sends a prompt, Claude compares the goal against the tool descriptions collected during discovery. If the user asks about stalled deals, Claude scans its menu (search_opportunities, get_account_health, create_task) and picks search_opportunities.

Treat every tool description as part of your prompt design. If two tools have overlapping descriptions, such as get_deals and fetch_opportunities, the model has to guess, and it will occasionally pick the wrong one. When exposing MCP primitives like tools, resources, and prompts from Salesforce, keep each tool description aligned whenever you change the underlying Flow, Apex class, or Agentforce topic.

3. Tool input construction

Picking the right tool is half the job. Next, the model extracts parameters from the user's sentence and packs them into a JSON payload that matches the tool's inputSchema. The excerpt below is an illustrative JSON-RPC 2.0 request (test exact field names against your own MCP server schema before deploying):

// Illustrative JSON-RPC 2.0 payload for tools/call
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "search_opportunities",
    "arguments": {
      "owner": "current_user",
      "minimum_value": 100000,
      "inactive_days": 14,
      "stage_status": "Open"
    }
  }
}

If a required field is missing, such as an Account_ID the user never mentioned, a well-instructed model should not invent an ID. It should either call a lookup tool first to retrieve the real ID or ask the user for clarification.

4. Tool call and execution (tools/call)

This stage trips up a lot of teams during design reviews. Claude never connects directly to your database, SOQL endpoint, or Apex classes.

Instead, the model emits a structured request asking to invoke search_opportunities with specific arguments. The host application (which runs the MCP Client) intercepts that request, applies any local policy or approval checks, and forwards the tools/call message to the MCP Server. The server then runs the Flow, Apex action, SOQL query, or Prompt Builder template under the authenticated user's credentials.

Common architecture mistake: who actually runs the tool?
Wrong framing: "Claude logs into Salesforce and executes the MCP tool directly."
Accurate framing: "Claude only produces a structured JSON request. The host application's MCP Client sends tools/call to the MCP Server, and the server runs the Salesforce logic inside the authenticated user's security boundary."

5. Tool result handling

After Salesforce or an external API finishes executing, the MCP Server wraps the output in a standard result object and sends it back to the client. The client appends that result to the conversation context so the model can read it.

Results usually come back in one of three forms:

  • Structured data, such as a JSON array of Opportunity records, account health metrics, or open cases.
  • An action confirmation containing a status flag and a newly created 18-character Salesforce Record ID (for example, TaskId: "00T8b00003Xyz12EAB").
  • An error payload marked with isError: true and a readable message like INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY or a validation rule error.

6. Reason, continue, or finish

Once the tool result lands in context, Claude checks whether it has answered the user's original goal. Three branches are common here:

  • If the user only asked to see stalled deals, Claude formats the returned records into a readable summary and ends the turn.
  • If more steps remain, as in the Sales Director scenario, Claude loops back to Step 2, picks create_task, and repeats the cycle until all three tasks exist.
  • If Salesforce returns a validation error (such as a missing due date), Claude reads the error text, adjusts the input if it has enough information, and retries, or explains the blocker to the user.

☁️ Inbound and outbound MCP patterns in Salesforce

When you plan how Claude, MCP, and Salesforce work together, it helps to separate traffic into two directions. Availability of specific Salesforce MCP features depends on your org edition, release version, and enabled Agentforce licenses, so verify current Setup options against official Salesforce release notes before building.

  • Inbound through Salesforce Hosted MCP Servers: external assistants like Claude or IDE agents connect into Salesforce. Depending on your org configuration, you can expose Agentforce agents (including agents authored with Agent Script Builder), Prompt Builder templates that run server-side with CRM grounding and Einstein Trust Layer protections, or deterministic Apex actions and autolaunched Flows for strict field updates and approvals.
  • Outbound through the Agentforce MCP Client: your internal Agentforce agents act as MCP Clients calling external MCP servers registered in Setup or sourced through partner listings such as AgentExchange (for example, Slack, Jira, or enrichment tools). Approved tools appear in the Agentforce Asset Library alongside native Flows and Apex actions.
🧭 360 Card: MCP tool calling architecture
  • Rule: keep model reasoning separate from system execution. Never allow a language model to run unvalidated database commands directly.
  • Benefit: one standard protocol replaces brittle one-off connectors across Claude, Agentforce, and third-party services.
  • Tradeoff: every exposed tool requires clear descriptions, tight JSON schemas, allowlist curation, and user-context OAuth enforcement.
  • Limit: loading dozens or hundreds of tools into one session increases token usage, adds latency, and raises the chance of wrong tool selection. Scope each agent topic to the smallest useful toolset.

🔑 Design takeaways to verify in your org

  • Keep tool descriptions short, distinct, and free of overlap so the model does not guess between two similar actions during Step 2.
  • Validate required fields inside your Flow or Apex handler even when the JSON schema marks them required, because models can still pass unexpected formats.
  • Return clear, specific error messages when isError: true so the model can tell the difference between a fixable input typo and a hard permission block.
  • Scope tool lists per topic or use an allowlist in Setup to prevent context bloat as your MCP server catalog grows.
  • Test multi-step chains in a sandbox with a non-admin user profile so you verify Organization-Wide Defaults, Sharing Rules, and Field-Level Security before going live.
Core rule:
The model writes the work order; the MCP Client and Server check the user's badge, run the machinery, and hand back the receipt.

❓ Questions and real-world architecture scenarios

Concise interview answer:
"MCP tool calling runs as a six-step loop: Discover, Select, Input, Call, Result, and Reason. Claude handles reasoning and formats the JSON arguments, while the MCP Client and Server execute the API call inside the user's OAuth and Salesforce sharing permissions."

Q1: How does Claude know the exact field names and data types a tool expects?

During Step 1 (Discovery), the MCP Server answers tools/list with a JSON Schema (inputSchema) for each tool. The host application includes those schemas in the model's context, so Claude sees which parameters are required, which are optional, and what data types or allowed values each field accepts.

Q2: What happens if a Salesforce API or Flow fails halfway through a tool call?

The MCP Server catches the exception and returns a tool result with isError: true and the underlying error message, such as a Salesforce validation rule failure. Claude reads that response in Step 6. If the problem is a formatting error it can correct, it retries with updated JSON; if the problem is missing business data or a permission block, it stops and explains the issue to the user.

Q3: The AI needs to read a customer's static contract document before making a recommendation. Should we use a Tool, a Prompt, or a Resource?

Use an MCP Resource for static or read-only reference content such as contract text, policy PDFs, or fixed account snapshots. Use a Tool when the model needs to pass parameters to search, filter, calculate, or modify live records.

Q4: Leadership wants every executive Account Review generated by the AI to follow the exact same corporate structure. Which MCP primitive solves this?

Use an MCP Prompt (or a Salesforce Prompt Builder Template exposed through MCP). Prompts give teams reusable templates with placeholders so every rep gets consistent structure and tone without writing long formatting instructions every time.

Q5: Can a single enterprise workflow combine Prompts, Resources, and Tools in the same turn?

Yes. A Prompt can define the structure of an executive briefing, a Resource can supply static product playbooks, and Tools can query live Salesforce Opportunities and create follow-up Tasks within the same conversation.

Q6: In Salesforce Hosted MCP Servers, when should I expose an Agentforce Agent vs. a Prompt Builder Template vs. an Apex/Flow Action as an MCP tool?

Match the tool type to the predictability of the task. Expose an Agentforce Agent when an external assistant should hand off a multi-step CRM goal that needs domain reasoning. Expose a Prompt Builder Template when you want text generated server-side inside Salesforce with CRM grounding and Einstein Trust Layer checks. Expose an Apex Action or Flow when the logic must be strictly deterministic, such as updating records, calculating discounts, or submitting approvals.

Q7: Can an AI agent use an MCP Tool to view or edit Salesforce records that the logged-in user doesn't have access to?

No, provided the integration uses OAuth 2.0 user-context authentication rather than an over-privileged shared integration user. Under user-context execution, Salesforce enforces Organization-Wide Defaults (OWD), Role Hierarchies, Sharing Rules, and Field-Level Security (FLS) just as it does in the UI.

Q8: What is "Context Bloat" in MCP tool calling, and how does Salesforce prevent it?

Context bloat happens when an MCP Client loads 100 or more tool definitions into the model's prompt at once. That consumes context tokens, slows responses, and causes the model to confuse similar tools during Step 2. In Salesforce, admins reduce this by allowlisting only the required tools in Setup, importing them into the Agentforce Asset Library, and attaching each action only to the relevant Agent Topic.

Q9: How do we stop an AI agent from accidentally calling a destructive tool, like deleting records or issuing a $50,000 refund?

Do not rely on system prompt instructions alone. Layer three controls: leave destructive delete tools off your MCP allowlist entirely, enforce hard dollar or status thresholds inside your underlying Flow or Apex code, and require human-in-the-loop confirmation in the MCP Host before any high-risk tools/call executes.

Q10: Follow-up connecting to MCP security: what happens if a webpage or CRM note contains a hidden prompt injection telling the AI to call an export tool and leak customer data?

Because the model reads tool results and user text in the same context window, untrusted text inside a Case comment or webpage can try to hijack Step 6 and trigger an unexpected tools/call. Defending against this requires least-privilege OAuth scopes, strict tool allowlists that exclude bulk-export actions unless genuinely needed, input validation on the MCP Server, and mandatory human approval before sensitive outbound calls run.

Was this article helpful?

Have a question or spotted a mistake? Ask here about this article

Found this guide useful? Buy me a coffee (opens in a new tab)

Comments

Questions, corrections and your own experience are all welcome.