Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions src/late/mcp/chatgpt_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@

import os
from datetime import datetime, timedelta, timezone
from typing import Any, Literal
from typing import Annotated, Any, Literal

import httpx
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
from fastmcp.server.dependencies import get_access_token
from fastmcp.tools import ToolResult
from mcp.types import TextContent, ToolAnnotations
from pydantic import BaseModel, Field
from pydantic import BaseModel, BeforeValidator, Field

from late.client.base import _retry_after_seconds
from late.mcp.auth import build_auth_provider, forget_rejected_token
Expand Down Expand Up @@ -52,6 +52,7 @@
_ACCOUNTS_PAGE_SIZE = 100
_ACCOUNT_LOOKUP_LIMIT = 25
_USERNAMES_PAGE_SIZE = 500
_POSTS_PAGE_SIZE_MAX = 50
_DAY_NAMES = [
"Monday",
"Tuesday",
Expand Down Expand Up @@ -468,6 +469,20 @@ async def _usernames(posts: list[dict[str, Any]]) -> dict[str, str]:
}


def _cap_posts_limit(value: Any) -> Any:
"""Clamp an oversized list_posts limit instead of rejecting it.

The advertised schema keeps ``maximum: 50`` (the definition OpenAI
approved), but ChatGPT regularly sends 100 or more anyway, and a
``less_than_equal`` error fails the whole call. This runs before the
``le`` check, so anything above the cap becomes the cap.
"""
is_number = isinstance(value, (int, float)) and not isinstance(value, bool)
if is_number and value > _POSTS_PAGE_SIZE_MAX:
return _POSTS_PAGE_SIZE_MAX
return value


def _media_items(media_urls: list[str] | None) -> list[dict[str, str]]:
return [media_item(url) for url in media_urls or []]

Expand Down Expand Up @@ -654,7 +669,9 @@ async def list_posts(
account_id: str | None = Field(
default=None, description="Only posts targeting this social account"
),
limit: int = Field(default=20, ge=1, le=50, description="Maximum posts to return"),
limit: Annotated[int, BeforeValidator(_cap_posts_limit)] = Field(
default=20, ge=1, le=_POSTS_PAGE_SIZE_MAX, description="Maximum posts to return"
),
) -> ToolResult:
params: dict[str, Any] = {"limit": limit, "page": 1, "sortBy": "scheduled-desc"}
if status:
Expand All @@ -675,7 +692,15 @@ async def list_posts(
+ ", ".join(t.platform for t in p.targets)
for p in posts
]
return _result(listing, f"{len(posts)} of {total} post(s):\n" + "\n".join(lines))
more = ""
if limit == _POSTS_PAGE_SIZE_MAX and total > len(posts):
more = (
f"\n{_POSTS_PAGE_SIZE_MAX} is the most one call returns (larger limits are "
"capped); these are the newest. Narrow with status or account_id to see others."
)
return _result(
listing, f"{len(posts)} of {total} post(s):\n" + "\n".join(lines) + more
)


@chatgpt_mcp.tool(
Expand Down
30 changes: 30 additions & 0 deletions tests/test_chatgpt_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,36 @@ async def test_get_post_takes_the_camelcase_post_id():
assert not result.is_error, result.content[0].text


@respx.mock
async def test_list_posts_clamps_an_oversized_limit_instead_of_rejecting_it():
# ChatGPT regularly asks for more than 50 posts; the call used to fail
# schema validation ("limit: less_than_equal") before reaching the API.
route = respx.get(f"{API}/v1/posts").mock(
return_value=httpx.Response(
200, json={"posts": [POST], "pagination": {"total": 120}}
)
)
result = await _call("list_posts", limit=100)
assert not result.is_error, result.content
assert route.calls.last.request.url.params["limit"] == "50"
assert result.structured_content["total"] == 120
text = result.content[0].text
assert "1 of 120" in text
assert "50 is the most one call returns" in text and "capped" in text


@respx.mock
async def test_list_posts_does_not_mention_clamping_for_a_normal_limit():
route = respx.get(f"{API}/v1/posts").mock(
return_value=httpx.Response(
200, json={"posts": [POST], "pagination": {"total": 1}}
)
)
result = await _call("list_posts", limit=10)
assert route.calls.last.request.url.params["limit"] == "10"
assert "capped" not in result.content[0].text


@respx.mock
async def test_schedule_post_requires_known_accounts_and_a_timezone():
respx.get(f"{API}/v1/accounts").mock(
Expand Down
Loading