@@ -892,6 +892,7 @@ def __init__(
892892 * ,
893893 tool_input_guardrails : list [ToolInputGuardrail [Any ]] | None = None ,
894894 tool_output_guardrails : list [ToolOutputGuardrail [Any ]] | None = None ,
895+ max_list_pages : int | None = None ,
895896 ):
896897 """
897898 Args:
@@ -935,6 +936,12 @@ def __init__(
935936 server before the tool is invoked.
936937 tool_output_guardrails: Optional list of guardrails applied to every tool on this
937938 server after the tool returns.
939+ max_list_pages: Maximum successful pages per automatic `list_tools()` or
940+ `list_prompts()` call. Set a positive integer to bound pagination; `None`
941+ (the default) applies no page limit. A final page at the limit succeeds;
942+ otherwise `UserError` is raised without returning or caching a partial list.
943+ Failed requests follow the existing retry policy and do not reset this budget.
944+ This does not limit page size or apply to explicit resource pagination.
938945 """
939946 mcp_compat .enable_legacy_httpx_compat ()
940947 super ().__init__ (
@@ -957,6 +964,12 @@ def __init__(
957964 # the public timeout attribute before a later connection attempt.
958965 _client_session_read_timeout (client_session_timeout_seconds )
959966 _validate_retry_backoff_seconds_max (retry_backoff_seconds_max )
967+ if max_list_pages is not None :
968+ if isinstance (max_list_pages , bool ) or not isinstance (max_list_pages , int ):
969+ raise TypeError ("max_list_pages must be a positive integer or None." )
970+ if max_list_pages < 1 :
971+ raise ValueError ("max_list_pages must be a positive integer or None." )
972+ self .max_list_pages = max_list_pages
960973 self .client_session_timeout_seconds = client_session_timeout_seconds
961974 self .max_retry_attempts = max_retry_attempts
962975 self .retry_backoff_seconds_base = retry_backoff_seconds_base
@@ -1454,23 +1467,28 @@ async def list_tools(
14541467 cursor : str | None = None
14551468 seen_cursors : set [str | None ] = set ()
14561469
1457- async def fetch_pages () -> bool :
1470+ async def fetch_pages () -> Literal [ "complete" , "repeated_cursor" , "page_limit" ] :
14581471 nonlocal cursor
14591472 while True :
1473+ if (
1474+ self .max_list_pages is not None
1475+ and len (seen_cursors ) >= self .max_list_pages
1476+ ):
1477+ return "page_limit"
14601478 result = await self ._list_tools_page (session , cursor )
14611479 tools .extend (result .tools )
14621480 seen_cursors .add (cursor )
14631481 next_cursor = result_next_cursor (result )
14641482 if next_cursor is None :
1465- return True
1483+ return "complete"
14661484 if next_cursor in seen_cursors :
1467- return False
1485+ return "repeated_cursor"
14681486 cursor = next_cursor
14691487
1470- pagination_complete = False
1488+ pagination_status : str | None = None
14711489 pagination_failure : BaseException | None = None
14721490 try :
1473- pagination_complete = await self ._run_with_retries (fetch_pages )
1491+ pagination_status = await self ._run_with_retries (fetch_pages )
14741492 except BaseException as error :
14751493 if cursor is None :
14761494 raise
@@ -1483,13 +1501,18 @@ async def fetch_pages() -> bool:
14831501 else :
14841502 pagination_failure = _credential_safe_exception_leaf (error )
14851503
1486- if pagination_failure is not None or not pagination_complete :
1504+ if pagination_failure is not None or pagination_status != "complete" :
14871505 cursor = None
14881506 seen_cursors .clear ()
14891507 tools .clear ()
14901508 del fetch_pages
14911509 if pagination_failure is not None :
14921510 raise pagination_failure from None
1511+ if pagination_status == "page_limit" :
1512+ raise UserError (
1513+ "MCP tool listing exceeded max_list_pages. Increase max_list_pages "
1514+ "to allow more pages, or check the server pagination."
1515+ ) from None
14931516 raise UserError (
14941517 f"MCP server '{ self ._error_name } ' returned a repeated cursor while "
14951518 "listing tools."
@@ -1646,9 +1669,13 @@ async def list_prompts(
16461669 seen_cursors : set [str | None ] = {None }
16471670 pagination_failure : BaseException | None = None
16481671 repeated_cursor = False
1672+ page_limit_reached = False
16491673 page : ListPromptsResult | None = None
16501674 next_cursor : str | None = None
16511675 while cursor is not None :
1676+ if self .max_list_pages is not None and len (seen_cursors ) >= self .max_list_pages :
1677+ page_limit_reached = True
1678+ break
16521679 try :
16531680 page = await self ._list_prompts_page (session , cursor )
16541681 except BaseException as error :
@@ -1669,7 +1696,7 @@ async def list_prompts(
16691696 break
16701697 cursor = next_cursor
16711698
1672- if pagination_failure is not None or repeated_cursor :
1699+ if pagination_failure is not None or repeated_cursor or page_limit_reached :
16731700 cursor = None
16741701 seen_cursors .clear ()
16751702 prompts .clear ()
@@ -1678,6 +1705,11 @@ async def list_prompts(
16781705 del result
16791706 if pagination_failure is not None :
16801707 raise pagination_failure from None
1708+ if page_limit_reached :
1709+ raise UserError (
1710+ "MCP prompt listing exceeded max_list_pages. Increase max_list_pages "
1711+ "to allow more pages, or check the server pagination."
1712+ ) from None
16811713 raise UserError (
16821714 f"MCP server '{ self ._error_name } ' returned a repeated cursor while listing prompts."
16831715 ) from None
@@ -1913,6 +1945,7 @@ def __init__(
19131945 * ,
19141946 tool_input_guardrails : list [ToolInputGuardrail [Any ]] | None = None ,
19151947 tool_output_guardrails : list [ToolOutputGuardrail [Any ]] | None = None ,
1948+ max_list_pages : int | None = None ,
19161949 ):
19171950 """Create a new MCP server based on the stdio transport.
19181951
@@ -1961,6 +1994,12 @@ def __init__(
19611994 server before the tool is invoked.
19621995 tool_output_guardrails: Optional list of guardrails applied to every tool on this
19631996 server after the tool returns.
1997+ max_list_pages: Maximum successful pages per automatic `list_tools()` or
1998+ `list_prompts()` call. Set a positive integer to bound pagination; `None`
1999+ (the default) applies no page limit. A final page at the limit succeeds;
2000+ otherwise `UserError` is raised without returning or caching a partial list.
2001+ Failed requests follow the existing retry policy and do not reset this budget.
2002+ This does not limit page size or apply to explicit resource pagination.
19642003 """
19652004 super ().__init__ (
19662005 cache_tools_list = cache_tools_list ,
@@ -1975,6 +2014,7 @@ def __init__(
19752014 tool_meta_resolver = tool_meta_resolver ,
19762015 custom_data_extractor = custom_data_extractor ,
19772016 retry_backoff_seconds_max = retry_backoff_seconds_max ,
2017+ max_list_pages = max_list_pages ,
19782018 tool_input_guardrails = tool_input_guardrails ,
19792019 tool_output_guardrails = tool_output_guardrails ,
19802020 )
@@ -2055,6 +2095,7 @@ def __init__(
20552095 * ,
20562096 tool_input_guardrails : list [ToolInputGuardrail [Any ]] | None = None ,
20572097 tool_output_guardrails : list [ToolOutputGuardrail [Any ]] | None = None ,
2098+ max_list_pages : int | None = None ,
20582099 ):
20592100 """Create a new MCP server based on the HTTP with SSE transport.
20602101
@@ -2105,6 +2146,12 @@ def __init__(
21052146 server before the tool is invoked.
21062147 tool_output_guardrails: Optional list of guardrails applied to every tool on this
21072148 server after the tool returns.
2149+ max_list_pages: Maximum successful pages per automatic `list_tools()` or
2150+ `list_prompts()` call. Set a positive integer to bound pagination; `None`
2151+ (the default) applies no page limit. A final page at the limit succeeds;
2152+ otherwise `UserError` is raised without returning or caching a partial list.
2153+ Failed requests follow the existing retry policy and do not reset this budget.
2154+ This does not limit page size or apply to explicit resource pagination.
21082155 """
21092156 super ().__init__ (
21102157 cache_tools_list = cache_tools_list ,
@@ -2119,6 +2166,7 @@ def __init__(
21192166 tool_meta_resolver = tool_meta_resolver ,
21202167 custom_data_extractor = custom_data_extractor ,
21212168 retry_backoff_seconds_max = retry_backoff_seconds_max ,
2169+ max_list_pages = max_list_pages ,
21222170 tool_input_guardrails = tool_input_guardrails ,
21232171 tool_output_guardrails = tool_output_guardrails ,
21242172 )
@@ -2225,6 +2273,7 @@ def __init__(
22252273 * ,
22262274 tool_input_guardrails : list [ToolInputGuardrail [Any ]] | None = None ,
22272275 tool_output_guardrails : list [ToolOutputGuardrail [Any ]] | None = None ,
2276+ max_list_pages : int | None = None ,
22282277 ):
22292278 """Create a new MCP server based on the Streamable HTTP transport.
22302279
@@ -2276,6 +2325,12 @@ def __init__(
22762325 server before the tool is invoked.
22772326 tool_output_guardrails: Optional list of guardrails applied to every tool on this
22782327 server after the tool returns.
2328+ max_list_pages: Maximum successful pages per automatic `list_tools()` or
2329+ `list_prompts()` call. Set a positive integer to bound pagination; `None`
2330+ (the default) applies no page limit. A final page at the limit succeeds;
2331+ otherwise `UserError` is raised without returning or caching a partial list.
2332+ Failed requests follow the existing retry policy and do not reset this budget.
2333+ This does not limit page size or apply to explicit resource pagination.
22792334 """
22802335 super ().__init__ (
22812336 cache_tools_list = cache_tools_list ,
@@ -2290,6 +2345,7 @@ def __init__(
22902345 tool_meta_resolver = tool_meta_resolver ,
22912346 custom_data_extractor = custom_data_extractor ,
22922347 retry_backoff_seconds_max = retry_backoff_seconds_max ,
2348+ max_list_pages = max_list_pages ,
22932349 tool_input_guardrails = tool_input_guardrails ,
22942350 tool_output_guardrails = tool_output_guardrails ,
22952351 )
0 commit comments