feedmcp-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
feedmcp/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .client import DEFAULT_BASE_URL, FeedMCPClient, FeedMCPError
2
+
3
+ __all__ = ["DEFAULT_BASE_URL", "FeedMCPClient", "FeedMCPError"]
4
+ __version__ = "0.1.0"
feedmcp/cli.py ADDED
@@ -0,0 +1,92 @@
1
+ """Minimal CLI for FeedMCP: find, describe, prices, status, call, account."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from typing import Dict, List, Optional
9
+
10
+ from .client import FeedMCPClient, FeedMCPError
11
+
12
+
13
+ def _parse_kv(pairs: List[str]) -> Dict[str, str]:
14
+ out: Dict[str, str] = {}
15
+ for item in pairs:
16
+ if "=" not in item:
17
+ raise ValueError(f"Expected key=value parameter, got: {item}")
18
+ k, v = item.split("=", 1)
19
+ out[k] = v
20
+ return out
21
+
22
+
23
+ def main(argv: Optional[List[str]] = None) -> int:
24
+ parser = argparse.ArgumentParser(
25
+ prog="feedmcp",
26
+ description="FeedMCP CLI — query 21 social media & ad library platforms (193 endpoints).",
27
+ )
28
+ parser.add_argument("--api-key", help="API key (defaults to FEEDMCP_API_KEY)")
29
+ parser.add_argument("--base-url", help="Override API base URL (defaults to https://api.feedmcp.com)")
30
+ sub = parser.add_subparsers(dest="cmd", required=True)
31
+
32
+ p_find = sub.add_parser("find", help="Search endpoints in plain words (free, no key)")
33
+ p_find.add_argument("query", help="Search query, e.g. 'tiktok comments'")
34
+ p_find.add_argument("--platform", help="Limit to one platform slug")
35
+
36
+ p_desc = sub.add_parser("describe", help="Show parameters, fields and price for one endpoint (free)")
37
+ p_desc.add_argument("endpoint", help="Endpoint ID, e.g. douyin.trends.list")
38
+
39
+ p_prices = sub.add_parser("prices", help="Show live USD price book (free)")
40
+ p_prices.add_argument("--platform", help="Filter by platform prefix, e.g. tiktok")
41
+
42
+ sub.add_parser("status", help="Show live health status for all 21 platforms (free)")
43
+ sub.add_parser("account", help="Show balance for FEEDMCP_API_KEY")
44
+
45
+ p_call = sub.add_parser("call", help="Call a data endpoint by ID (requires FEEDMCP_API_KEY)")
46
+ p_call.add_argument("endpoint", help="Endpoint ID, e.g. douyin.trends.list")
47
+ p_call.add_argument("-p", "--param", action="append", default=[], help="Query parameter as key=value (repeatable)")
48
+ p_call.add_argument("--max-price", help="Maximum USD allowed for this call (X-Max-Price)")
49
+ p_call.add_argument("--idempotency-key", help="Idempotency-Key for safe retries")
50
+ p_call.add_argument("--view", choices=["standard", "full"], help="Optional response view")
51
+
52
+ args = parser.parse_args(argv)
53
+ client = FeedMCPClient(api_key=args.api_key, base_url=args.base_url)
54
+
55
+ try:
56
+ if args.cmd == "find":
57
+ out = client.find(args.query, platform=args.platform)
58
+ elif args.cmd == "describe":
59
+ out = client.describe(args.endpoint)
60
+ elif args.cmd == "prices":
61
+ out = client.prices()
62
+ if args.platform:
63
+ prefix = args.platform + "."
64
+ out["endpoints"] = [e for e in out.get("endpoints", []) if e.get("id", "").startswith(prefix)]
65
+ elif args.cmd == "status":
66
+ out = client.status()
67
+ elif args.cmd == "account":
68
+ out = client.account()
69
+ elif args.cmd == "call":
70
+ params = _parse_kv(args.param)
71
+ out = client.call(
72
+ args.endpoint,
73
+ params,
74
+ max_price=args.max_price,
75
+ idempotency_key=args.idempotency_key,
76
+ view=args.view,
77
+ )
78
+ else:
79
+ parser.print_help()
80
+ return 2
81
+ print(json.dumps(out, ensure_ascii=False, indent=2))
82
+ return 0
83
+ except (FeedMCPError, ValueError) as exc:
84
+ if isinstance(exc, FeedMCPError):
85
+ print(json.dumps({"error": exc.code, "message": str(exc), "charged": exc.charged, "retry": exc.retry, "top_up_url": exc.top_up_url}, ensure_ascii=False, indent=2), file=sys.stderr)
86
+ else:
87
+ print(str(exc), file=sys.stderr)
88
+ return 1
89
+
90
+
91
+ if __name__ == "__main__":
92
+ raise SystemExit(main())
feedmcp/client.py ADDED
@@ -0,0 +1,200 @@
1
+ """Zero-dependency HTTP client for the FeedMCP API (https://feedmcp.com)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import ssl
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ import uuid
12
+ from typing import Any, Dict, Iterator, Optional
13
+
14
+ DEFAULT_BASE_URL = "https://api.feedmcp.com"
15
+
16
+
17
+ def _ssl_context() -> ssl.SSLContext:
18
+ try:
19
+ import certifi # type: ignore
20
+
21
+ return ssl.create_default_context(cafile=certifi.where())
22
+ except Exception:
23
+ return ssl.create_default_context()
24
+
25
+
26
+ class FeedMCPError(Exception):
27
+ """Structured error returned by the FeedMCP API."""
28
+
29
+ def __init__(
30
+ self,
31
+ message: str,
32
+ *,
33
+ status: int = 0,
34
+ code: str = "unknown_error",
35
+ charged: Optional[bool] = False,
36
+ retry: Optional[str] = None,
37
+ retry_after_seconds: Optional[int] = None,
38
+ request_id: Optional[str] = None,
39
+ top_up_url: Optional[str] = None,
40
+ body: Optional[Dict[str, Any]] = None,
41
+ ) -> None:
42
+ super().__init__(message)
43
+ self.status = status
44
+ self.code = code
45
+ self.charged = charged
46
+ self.retry = retry
47
+ self.retry_after_seconds = retry_after_seconds
48
+ self.request_id = request_id
49
+ self.top_up_url = top_up_url
50
+ self.body = body or {}
51
+
52
+
53
+ class FeedMCPClient:
54
+ """Thin client for FeedMCP discovery and pay-per-call data endpoints."""
55
+
56
+ def __init__(
57
+ self,
58
+ api_key: Optional[str] = None,
59
+ *,
60
+ base_url: Optional[str] = None,
61
+ timeout: float = 30.0,
62
+ ) -> None:
63
+ self.api_key = api_key if api_key is not None else os.environ.get("FEEDMCP_API_KEY")
64
+ self.base_url = (base_url or os.environ.get("FEEDMCP_API_URL") or DEFAULT_BASE_URL).rstrip("/")
65
+ self.timeout = timeout
66
+
67
+ def _request(
68
+ self,
69
+ path: str,
70
+ *,
71
+ params: Optional[Dict[str, Any]] = None,
72
+ auth: bool = False,
73
+ max_price: Optional[str] = None,
74
+ idempotency_key: Optional[str] = None,
75
+ ) -> Dict[str, Any]:
76
+ query_items = [(k, str(v)) for k, v in (params or {}).items() if v is not None]
77
+ qs = urllib.parse.urlencode(query_items)
78
+ url = f"{self.base_url}{path}" + (f"?{qs}" if qs else "")
79
+
80
+ headers = {
81
+ "Accept": "application/json",
82
+ "User-Agent": "feedmcp-python/0.1.0",
83
+ }
84
+ if auth:
85
+ if not self.api_key:
86
+ raise FeedMCPError(
87
+ "Missing API key. Set FEEDMCP_API_KEY or pass api_key=... (get $0.10 free trial at https://feedmcp.com/console/keys/).",
88
+ status=401,
89
+ code="unauthorized",
90
+ charged=False,
91
+ retry="after_fix",
92
+ )
93
+ headers["Authorization"] = f"Bearer {self.api_key}"
94
+ if max_price is not None:
95
+ headers["X-Max-Price"] = str(max_price)
96
+ if idempotency_key is not None:
97
+ headers["Idempotency-Key"] = str(idempotency_key)
98
+
99
+ req = urllib.request.Request(url, headers=headers, method="GET")
100
+ try:
101
+ ctx = _ssl_context() if url.startswith("https://") else None
102
+ with urllib.request.urlopen(req, timeout=self.timeout, context=ctx) as resp:
103
+ raw = resp.read().decode("utf-8")
104
+ return json.loads(raw) if raw else {}
105
+ except urllib.error.HTTPError as exc:
106
+ raw = exc.read().decode("utf-8", errors="replace")
107
+ try:
108
+ data = json.loads(raw) if raw else {}
109
+ except json.JSONDecodeError:
110
+ data = {"message": raw or str(exc)}
111
+ raise FeedMCPError(
112
+ data.get("message") or f"HTTP {exc.code}",
113
+ status=exc.code,
114
+ code=data.get("code") or f"http_{exc.code}",
115
+ charged=data.get("charged", False),
116
+ retry=data.get("retry"),
117
+ retry_after_seconds=data.get("retry_after_seconds"),
118
+ request_id=data.get("request_id"),
119
+ top_up_url=data.get("top_up_url"),
120
+ body=data,
121
+ ) from exc
122
+
123
+ # ---------------- Free discovery (no API key required) ----------------
124
+
125
+ def catalog(self) -> Dict[str, Any]:
126
+ """Return the full catalog of platforms, endpoints, parameters and prices (free)."""
127
+ return self._request("/v1/catalog")
128
+
129
+ def find(self, query: str, *, platform: Optional[str] = None) -> Dict[str, Any]:
130
+ """Search endpoints in plain words (free, no key required)."""
131
+ return self._request("/v1/catalog/search", params={"q": query, "platform": platform})
132
+
133
+ def describe(self, endpoint_id: str) -> Dict[str, Any]:
134
+ """Inspect parameters, response shape and price for one endpoint ID (free)."""
135
+ safe = urllib.parse.quote(endpoint_id, safe="")
136
+ return self._request(f"/v1/catalog/endpoints/{safe}")
137
+
138
+ def prices(self) -> Dict[str, Any]:
139
+ """Return the live USD price book for all endpoints (free)."""
140
+ return self._request("/v1/catalog/prices")
141
+
142
+ def status(self) -> Dict[str, Any]:
143
+ """Return current health status for all 21 platforms (free)."""
144
+ return self._request("/v1/catalog/status")
145
+
146
+ # ---------------- Authenticated endpoints ----------------
147
+
148
+ def account(self) -> Dict[str, Any]:
149
+ """Check remaining account balance and email (requires API key)."""
150
+ return self._request("/v1/me", auth=True)
151
+
152
+ def call(
153
+ self,
154
+ endpoint_id: str,
155
+ params: Optional[Dict[str, Any]] = None,
156
+ *,
157
+ max_price: Optional[str] = None,
158
+ idempotency_key: Optional[str] = None,
159
+ view: Optional[str] = None,
160
+ ) -> Dict[str, Any]:
161
+ """Call any FeedMCP data endpoint by ID (e.g. 'tiktok.videos.comments.list')."""
162
+ path = "/v1/" + endpoint_id.lstrip("/").replace(".", "/")
163
+ merged = dict(params or {})
164
+ if view is not None:
165
+ merged["view"] = view
166
+ return self._request(
167
+ path,
168
+ params=merged,
169
+ auth=True,
170
+ max_price=max_price,
171
+ idempotency_key=idempotency_key,
172
+ )
173
+
174
+ def paginate(
175
+ self,
176
+ endpoint_id: str,
177
+ params: Optional[Dict[str, Any]] = None,
178
+ *,
179
+ max_pages: int = 5,
180
+ max_price: Optional[str] = None,
181
+ view: Optional[str] = None,
182
+ ) -> Iterator[Dict[str, Any]]:
183
+ """Yield up to max_pages pages from a list endpoint using page.next_cursor."""
184
+ cursor: Optional[str] = None
185
+ for _ in range(max_pages):
186
+ page_params = dict(params or {})
187
+ if cursor is not None:
188
+ page_params["cursor"] = cursor
189
+ body = self.call(
190
+ endpoint_id,
191
+ page_params,
192
+ max_price=max_price,
193
+ idempotency_key=str(uuid.uuid4()),
194
+ view=view,
195
+ )
196
+ yield body
197
+ page = body.get("page") or {}
198
+ cursor = page.get("next_cursor")
199
+ if not cursor or not page.get("has_more", True):
200
+ break
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: feedmcp-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK and CLI for FeedMCP — unified social media, creator marketing, ad library and e-commerce public data across 21 platforms (193 endpoints).
5
+ Author-email: FeedMCP <support@feedmcp.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://feedmcp.com
8
+ Project-URL: Documentation, https://feedmcp.com/docs/
9
+ Project-URL: Repository, https://github.com/feedmcp/feedmcp
10
+ Project-URL: Issues, https://github.com/feedmcp/feedmcp/issues
11
+ Keywords: feedmcp,mcp,social-media-api,tiktok,youtube,instagram,twitter,xiaohongshu,douyin,wechat,ai-agent
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # feedmcp (Python SDK & CLI)
28
+
29
+ Official zero-dependency Python client and CLI for [FeedMCP](https://feedmcp.com) — unified public social media, creator marketing, ad library, and e-commerce data across 21 global and Chinese platforms (193 endpoints).
30
+
31
+ > Note: FeedMCP (`feedmcp.com`) is a social media data MCP server and HTTP API, not an RSS feed reader.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install feedmcp-sdk
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ```python
42
+ from feedmcp import FeedMCPClient
43
+
44
+ client = FeedMCPClient() # reads FEEDMCP_API_KEY from environment
45
+
46
+ # 1. Free discovery (no API key required)
47
+ matches = client.find("tiktok comments")
48
+ spec = client.describe("tiktok.videos.comments.list")
49
+
50
+ # 2. Paid call with per-call spend cap (failed calls are free)
51
+ res = client.call(
52
+ "tiktok.videos.comments.list",
53
+ {"id": "7700200904678559006"},
54
+ max_price="0.002",
55
+ )
56
+ print(res["data"]["items"], res["meta"]["billing"])
57
+
58
+ # 3. Auto-paginate with cursor
59
+ for page in client.paginate("douyin.videos.comments.list", {"id": "7372484719365098803"}, max_pages=3, max_price="0.002"):
60
+ print(len(page["data"]["items"]))
61
+ ```
62
+
63
+ ## CLI
64
+
65
+ ```bash
66
+ feedmcp find "xiaohongshu comments"
67
+ feedmcp describe douyin.trends.list
68
+ feedmcp prices --platform tiktok
69
+ feedmcp status
70
+ feedmcp call douyin.trends.list --max-price 0.002
71
+ feedmcp account
72
+ ```
73
+
74
+ Get a free `$0.10` trial API key (no card required): https://feedmcp.com/console/keys/
@@ -0,0 +1,9 @@
1
+ feedmcp/__init__.py,sha256=TvRxPYNm-NRxbUsYS0SCScXjIFfddBj6tDFtLs6Bgl4,153
2
+ feedmcp/cli.py,sha256=Vs_jx39I8sssg3BAx5aBc6IVfZUsHXKrPRoSJ-cDzyM,3886
3
+ feedmcp/client.py,sha256=yVUy0fOKQUoojkLZZhjwPboe4S3DeoOSFuhpQs5Cl14,7173
4
+ feedmcp_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=vfxUG2hgFRsV4e3ntq7UbEcrClbEOF34TCDct1WS960,1064
5
+ feedmcp_sdk-0.1.0.dist-info/METADATA,sha256=9psq3A62KQUSuc8WedhR-ZonJCdyKvsmK8pvWoFK3KE,2626
6
+ feedmcp_sdk-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ feedmcp_sdk-0.1.0.dist-info/entry_points.txt,sha256=3iTgQ2JPScPf_F7vMn5LOWES8HSlaOU8qFNjgad46gU,45
8
+ feedmcp_sdk-0.1.0.dist-info/top_level.txt,sha256=H_-28wcfddsxjzm2w-d4mnuM2L-1w91wfT1bJM7EhRI,8
9
+ feedmcp_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ feedmcp = feedmcp.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FeedMCP
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ feedmcp