Skip to content

[Feature]: Response Caching for tools() and resources() #23

@MaestroError

Description

@MaestroError

Summary

Priority: 🟡 MEDIUM
Impact: 99% reduction in latency for repeated calls
Difficulty: Easy

Usage Examples

After implementation, users can:

// Default behavior - caching enabled
$tools = $client->connect('github')->tools(); // Fetches from server
$toolsAgain = $client->tools(); // Returns cached result (fast!)

// Force fresh data
$freshTools = $client->tools(fresh: true); // Bypasses cache

// Disable caching entirely
$client->disableCache();
$tools1 = $client->tools(); // Fetches from server
$tools2 = $client->tools(); // Fetches from server again

// Re-enable caching
$client->enableCache();

// Clear cache manually
$client->clearCache();

Testing Checklist

  • First call to tools() fetches from server
  • Second call to tools() returns cached result
  • fresh=true parameter bypasses cache
  • clearCache() clears cached data
  • disableCache() prevents caching
  • enableCache() re-enables caching
  • Cache is cleared when switching servers
  • Cache keys include server name (different servers don't share cache)

Problem

The tools() and resources() methods make a network/process request every single time they're called, even though:

  1. Tool definitions rarely change during a session
  2. Resource lists are typically static
  3. Users often call these methods multiple times (e.g., to check available tools before calling them)

Example of Inefficiency

$client = MCPClient::connect('github');

// First call - fetches from server
$tools = $client->tools();

// Check if specific tool exists
if ($tools->only('search_repos')->count() > 0) {
    // Second call - fetches AGAIN from server (unnecessary!)
    $allTools = $client->tools();
    // ... do something
}

Proposed Solution

Add an optional caching layer to MCPClient that caches the results of tools() and resources() calls.

Implementation Steps

Step 1: Add Cache Properties to MCPClient

Modify src/MCPClient.php:
Add cache properties:
private array $cache = [];
private bool $cacheEnabled = true;

Step 2: Add Cache Helper Methods

Add these methods to src/MCPClient.php:

enableCache
disableCache
clearCache
getCacheKey

Step 3: Update tools() & resources() Methods to Use Cache

Step 4: Update connect() to Clear Cache When Switching Servers

Step 5: Add Tests

Add to tests/MCPClient/MCPClientTest.php:

Alternatives Considered

No response

Package Version

1

PHP Version

8.4

Laravel Version

12

Notes

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions