Solving Context Loss When Agents Fetch Large Datasets

KeyAPIClaudeFree · Updated 2026-11-24 · 15 min read

Flowchart illustrating the pagination loop process
Visualizing the loop that agents use to fetch multiple pages of data.

When building an MCP server, the most common failure point is not the model itself, but the tool interface. A developer might write a tool that fetches all relevant data from a database and feeds it directly to the LLM. This works fine for small datasets, but when the result set grows, the tool returns a massive payload that exceeds the context window or breaks the agent’s ability to process the response efficiently. The core issue arises because many client applications, including popular chat interfaces, struggle with paginated responses. If a tool returns a single page of results, the agent may terminate the conversation loop prematurely, assuming the task is complete. If the tool returns all data at once, the response can become too large, causing timeouts or truncation. The agent ends up looping, fetching page after page, without ever synthesizing the final answer.

The solution is to handle pagination explicitly within the MCP server’s tool definition. By designing tools that return structured, paginated data with clear metadata, you allow the agent to make informed decisions about when to stop fetching and start reasoning. This approach ensures that the coding agent can process large datasets correctly, maintaining context and delivering accurate results without getting stuck in infinite loops or losing critical information. Unlike commercial offerings that might offer managed solutions, building your own MCP server requires careful attention to these details. While this site uses the brand name Claude in its domain, it is not affiliated with Anthropic, and the principles here apply to any open-compatible model.

This guide walks through the technical implementation of pagination in Python-based MCP servers. We will cover schema design, handler logic, agent-side looping, and error handling. By the end, you will have a robust tool that can handle large datasets without overwhelming the agent's context window. You can also check out our guide on Local vs Managed MCP Servers for Coding Agents to understand where your server fits in the broader ecosystem.

Frequently asked questions

What is MCP pagination?

MCP pagination is a pattern where tools return data in discrete chunks rather than all at once. Each chunk includes metadata like total count and current page number. This allows the agent to manage context windows effectively and decide when to stop fetching data, preventing context overflow and ensuring reliable processing of large datasets.

How does client-side pagination differ from server-side pagination?

Server-side pagination moves the logic to the MCP server, which returns only the requested chunk of data. Client-side pagination requires the agent to fetch the entire dataset and then split it locally. Server-side is more efficient for large datasets because it reduces network transfer and context usage, while client-side can be simpler but risks exceeding token limits quickly.

Why do agents hang after fetching a page?

Agents often hang because they interpret a partial response as the final answer. If a tool returns a single page without clear continuation markers, the agent assumes the task is done. It then terminates the conversation loop, leaving the user waiting for a summary that never comes because the agent has not yet processed the remaining data pages.

What is the best way to structure pagination metadata?

The best structure includes total items, current page number, items per page, and a boolean flag indicating if more data exists. This allows the agent to calculate exactly how many requests are needed. Avoid complex cursor strings unless necessary; simple offset-based pagination is easier for agents to reason about and implement correctly in loops.

Which is better: offset or cursor-based pagination?

Offset-based pagination is simpler for agents to implement because it uses integers. Cursor-based pagination is better for data consistency if records change frequently. For most coding agent use cases, offset-based pagination is preferred due to its simplicity, but cursor-based is superior for large, frequently updated datasets where data integrity during iteration is critical.

How does pagination affect token usage?

Pagination significantly reduces token usage by limiting the payload size per request. Instead of sending a massive JSON object, the agent receives small chunks. This keeps the context window clear for reasoning and reduces the risk of truncation. It also allows the agent to process data in manageable batches, improving accuracy and reducing latency for each individual tool call.

What happens if the MCP server returns invalid pagination?

If the server returns inconsistent metadata, such as a page number that exceeds the total, the agent may crash or enter an infinite loop. It might also return partial data, leading to incomplete analysis. Robust pagination requires strict validation of bounds and consistent metadata updates to ensure the agent can trust the structure and terminate correctly when data is exhausted.

Why is pagination important for coding agents?

Coding agents often need to process large codebases or log files. Without pagination, the agent might receive a response that exceeds the context window, leading to lost information. Pagination ensures that the agent can systematically review all relevant data, maintaining a clear understanding of the entire dataset without losing track of earlier sections due to context overflow.

Step by step

  1. Define Schema — Create an MCP tool schema with input parameters for page and size, and an output structure including data and metadata with a has_more flag.
  2. Implement Handler — Write a Python handler that queries the database with offset and limit, calculates total count, and returns the paginated data with accurate metadata.
  3. Test Edge Cases — Test the tool with empty datasets, single-page datasets, and multi-page datasets to ensure the has_more flag and total count are correct in all scenarios.
  4. Integrate Agent Logic — Implement agent-side logic to loop through pages until has_more is false, storing data for final processing and managing context window usage effectively.

Understanding the Pagination Problem in MCP

When an MCP tool fetches data from a database, it often returns a raw list of objects. If this list contains thousands of items, the resulting JSON payload can be enormous. The agent receives this payload, processes it, and then attempts to generate a response. However, if the payload is too large, it may exceed the context window, leading to truncation or errors. The agent might also struggle to parse the data correctly, leading to incomplete or inaccurate results.

Another common issue is the agent’s interpretation of the response. If the tool returns a single page of data, the agent might assume that this is the complete dataset. It then proceeds to analyze the data and generate a summary, unaware that there are more pages available. This leads to incomplete analysis, as the agent has only seen a fraction of the total data. The user is left with a response that feels incomplete, even though the tool worked correctly. See our article on Why Is the API Throwing Errors During Critical Work? for more on common API issues.

The Context Window Constraint

The context window is a finite resource. When a tool returns a large dataset, it consumes a significant portion of the available tokens. This leaves less room for the agent’s reasoning and response generation. If the dataset is too large, the agent may truncate the data, losing critical information. Pagination helps by breaking the data into smaller, manageable chunks that fit within the context window, ensuring that all data is processed accurately.

Agent Loop Behavior

Agents are designed to loop until a task is complete. However, if the pagination metadata is unclear, the agent may not know when to stop. It might continue fetching pages indefinitely, leading to inefficiency and increased latency. Clear pagination metadata allows the agent to calculate the total number of pages and stop when all data has been fetched. This ensures that the agent completes the task efficiently without wasting resources.

Designing Paginated MCP Tools

To implement pagination effectively, you need to design your MCP tools with clear input and output structures. The input should include parameters for page number, page size, and optionally a cursor. The output should include the data for the current page, along with metadata such as the total number of items, the current page number, and a flag indicating if more data is available. This structure allows the agent to make informed decisions about when to fetch the next page.

It is crucial to ensure that the pagination metadata is consistent and accurate. If the total count is incorrect, the agent may fetch too many or too few pages. Similarly, if the page size varies, the agent may struggle to calculate the total number of requests. Standardizing these parameters helps the agent reason about the data more effectively, reducing the likelihood of errors and improving the overall user experience. You can also read about Why Does Payment Keep Failing on the Bill Page? to understand how billing impacts API usage.

Input Parameters

The input parameters should include page_number, page_size, and optionally a cursor. The page_number should be an integer starting from 1. The page_size should be a reasonable default, such as 50 or 100 items, to balance between network efficiency and context usage. The cursor, if used, should be a string that uniquely identifies the next set of data. These parameters should be optional, with sensible defaults to simplify the agent’s usage.

Output Structure

The output should include a data array containing the current page’s items, a metadata object with total_count, current_page, and has_more. The has_more flag is critical, as it tells the agent whether it needs to fetch the next page. The metadata should also include the page_size used, allowing the agent to calculate the total number of pages accurately. This structure ensures that the agent has all the information it needs to manage pagination correctly.

Magnifying glass over documents representing data analysis
Agents must inspect each page carefully to ensure no data is missed.

Implementing Pagination in Python MCP Servers

Implementing pagination in a Python MCP server involves defining the tool schema and the corresponding handler function. The schema should specify the input parameters and the output structure, including the metadata fields. The handler function should query the database, apply the pagination logic, and return the result in the specified format. This ensures that the agent receives consistent, well-structured data that it can process reliably.

It is important to handle edge cases, such as when the page number exceeds the total number of pages or when the page size is larger than the remaining data. The handler should return an empty data array and set has_more to false in these cases. This allows the agent to recognize that there is no more data to fetch and terminate the loop correctly. Proper error handling ensures that the agent does not crash or enter an infinite loop due to unexpected data conditions.

Defining the Tool Schema

The tool schema should define the input parameters as optional integers with default values. The output schema should include a data array and a metadata object. The metadata object should contain total_count, current_page, page_size, and has_more. This structure ensures that the agent can parse the response easily and make decisions based on the metadata. Clear schema definitions reduce ambiguity and improve the agent’s ability to process the data correctly.

Writing the Handler Function

The handler function should accept the input parameters, query the database with offset and limit, and construct the response object. It should calculate the total count and determine if more data exists. The function should return the data and metadata in the specified format. Error handling should be included to catch database errors and return appropriate error messages. This ensures that the agent receives valid data or a clear error, allowing it to handle failures gracefully.

from mcp.server import MCPApp
import sqlite3

app = MCPApp()

@app.tool()
def fetch_data(page: int = 1, page_size: int = 50) -> dict:
    conn = sqlite3.connect('data.db')
    cursor = conn.cursor()
    
    # Get total count
    cursor.execute('SELECT COUNT(*) FROM items')
    total_count = cursor.fetchone()[0]
    
    # Calculate offset
    offset = (page - 1) * page_size
    
    # Fetch page data
    cursor.execute('SELECT * FROM items LIMIT ? OFFSET ?', (page_size, offset))
    data = [dict(row) for row in cursor.fetchall()]
    
    # Determine if more data exists
    has_more = offset + len(data) < total_count
    
    conn.close()
    
    return {
        'data': data,
        'metadata': {
            'total_count': total_count,
            'current_page': page,
            'page_size': page_size,
            'has_more': has_more
        }
    }

Agent-Side Pagination Logic

Once the MCP server returns paginated data, the agent needs to implement logic to fetch all pages and process the data. The agent should check the has_more flag in the metadata. If true, it should increment the page number and fetch the next page. This process continues until has_more is false. The agent should store the data from each page in a list for later processing.

It is important for the agent to manage its context window effectively. Fetching too many pages at once may exceed the context limit. The agent should consider processing each page as it is fetched, or batch them in manageable chunks. This ensures that the agent does not run out of context space and can generate accurate responses based on the complete dataset. Proper context management is key to handling large datasets successfully. Check How to Keep Coding When the Session Limit Resets for tips on managing session boundaries.

Fetching Multiple Pages

The agent should implement a loop that continues fetching pages until has_more is false. Each iteration should increment the page number and call the tool with the new parameters. The agent should store the data from each response in a list. This ensures that all data is collected before processing. The loop should also handle errors gracefully, retrying failed requests if necessary to ensure data completeness.

Processing Collected Data

After fetching all pages, the agent should process the collected data. This may involve filtering, sorting, or aggregating the data to generate the final response. The agent should ensure that the processed data fits within the context window for the final response. If the data is too large, the agent may need to summarize or truncate it intelligently. This step ensures that the agent provides a useful and accurate response to the user.

JSON structure on a screen representing API response
The API response structure must be clear for the agent to parse correctly.

Handling Edge Cases and Errors

Edge cases can disrupt pagination if not handled properly. For example, if the database returns fewer items than the page size on the last page, the agent should recognize this and stop fetching. If the total count is zero, the agent should return an empty result immediately. These edge cases ensure that the agent does not waste resources fetching empty pages or getting stuck in a loop.

Error handling is crucial for robust pagination. If a request fails, the agent should retry the request a limited number of times before giving up. If the server returns an error, the agent should log the error and inform the user. This ensures that the user is aware of any issues and can take appropriate action. Proper error handling improves the reliability of the MCP server and enhances the user experience.

Handling Empty Results

If the database returns no data, the tool should return an empty data array and set total_count to zero. The agent should recognize this and stop fetching immediately. This prevents unnecessary requests and saves resources. The agent should also inform the user that no data was found, providing a clear and helpful response. Handling empty results gracefully ensures that the agent behaves predictably even when no data is available.

Retrying Failed Requests

If a request fails, the agent should retry it with a short delay. It should limit the number of retries to avoid infinite loops. If all retries fail, the agent should report the error to the user. This ensures that temporary network issues do not prevent the agent from completing the task. Retrying failed requests improves the reliability of the pagination process and ensures that data is fetched correctly.

Optimizing for Performance and Cost

Pagination can significantly impact performance and cost. Fetching too many pages can lead to high latency and increased token usage. By optimizing the page size and reducing the number of requests, you can improve efficiency. A larger page size reduces the number of requests but increases the payload size. A smaller page size increases the number of requests but reduces the payload size. Finding the right balance is key to optimizing performance.

Token usage is a critical cost factor. Each request consumes tokens for the input and output. By reducing the number of requests, you can lower the token cost. However, if the page size is too large, the response may exceed the context window, leading to errors. It is important to test different page sizes and measure the impact on latency and token usage. This ensures that the MCP server operates efficiently without incurring unnecessary costs. See Why Does It Say Limit Reached With Usage Remaining? for more on usage limits.

Balancing Page Size

The page size should be chosen based on the typical dataset size and the context window limit. A page size of 50-100 items is often a good balance between network efficiency and context usage. Larger page sizes reduce the number of requests but increase the risk of context overflow. Smaller page sizes increase the number of requests but reduce the payload size. Testing different page sizes helps find the optimal balance for your specific use case.

Reducing Token Usage

Token usage can be reduced by minimizing the payload size and the number of requests. Using efficient data formats, such as JSON, and removing unnecessary fields can help. Additionally, processing data in smaller chunks allows the agent to generate responses more efficiently. This reduces the overall token consumption and lowers the cost. Monitoring token usage helps identify areas for optimization and ensures that the MCP server operates within budget.

Gears representing server and agent interaction
The server and agent must work together seamlessly for pagination to work.

Testing and Debugging Pagination

Testing pagination is essential to ensure that it works correctly. You should test with various dataset sizes, page sizes, and edge cases. Check that the agent fetches all pages correctly and processes the data accurately. Verify that the metadata is consistent and that the agent stops fetching when has_more is false. This ensures that the pagination logic is robust and reliable.

Debugging pagination issues often involves logging the requests and responses. Check the metadata to ensure that it is accurate. Verify that the agent’s loop terminates correctly. If the agent gets stuck, check the has_more flag and the page number calculation. Logging helps identify where the pagination logic fails and allows you to fix the issue. Proper testing and debugging ensure that the MCP server performs reliably under various conditions.

Unit Testing Tools

Unit tests should verify that the tool returns correct data and metadata for various inputs. Test with empty datasets, single-page datasets, and multi-page datasets. Ensure that the has_more flag is set correctly and that the total count is accurate. Unit tests provide confidence that the tool behaves as expected and help catch regressions early. Regular testing ensures that the pagination logic remains robust as the codebase evolves.

Integration Testing with Agents

Integration tests should verify that the agent correctly fetches and processes paginated data. Simulate large datasets and check that the agent completes the task without errors. Monitor the context window usage and token consumption. Ensure that the agent generates accurate responses based on the complete dataset. Integration tests provide a holistic view of the pagination system and ensure that it works seamlessly with the agent.

Best Practices for MCP Pagination

Following best practices ensures that your MCP server’s pagination is efficient, reliable, and easy to use. Use clear and consistent metadata structures. Implement robust error handling and retry logic. Optimize page sizes based on your specific use case. Test thoroughly with various datasets and edge cases. These practices help ensure that the agent can process large datasets correctly and provide accurate responses to users.

Documentation is also important. Clearly document the pagination parameters and expected behavior. This helps developers and agents understand how to use the tool correctly. Good documentation reduces confusion and improves the user experience. By following these best practices, you can build a robust MCP server that handles pagination effectively and supports your coding agents in processing large datasets. You might also want to check Claude Code vs Aider With Open Source Models for comparisons on coding tools.

Consistent Metadata

Consistent metadata structures make it easier for agents to parse and process responses. Use standard field names like total_count, current_page, and has_more. Avoid custom or ambiguous fields that may confuse the agent. Consistency reduces the cognitive load on the agent and improves the reliability of the pagination logic. This ensures that the agent can handle pagination correctly across different tools and datasets.

Clear Documentation

Clear documentation helps developers and agents understand how to use the tool. Document the input parameters, output structure, and edge cases. Provide examples of how to fetch multiple pages. Good documentation reduces the learning curve and improves the user experience. It also helps developers debug issues more quickly. Investing in clear documentation ensures that the MCP server is easy to use and maintain.

Bar chart showing token usage trends
Monitoring token usage helps optimize pagination efficiency.
Try the free API

Test the keyless API right now and see how fast it is.

Read also