produck 0.1.0__tar.gz
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.
- produck-0.1.0/.gitignore +1 -0
- produck-0.1.0/LICENSE +21 -0
- produck-0.1.0/PKG-INFO +92 -0
- produck-0.1.0/README.md +69 -0
- produck-0.1.0/pyproject.toml +32 -0
- produck-0.1.0/src/product/__init__.py +15 -0
- produck-0.1.0/src/product/cli.py +72 -0
- produck-0.1.0/src/product/client.py +248 -0
- produck-0.1.0/src/product/mcp_server.py +158 -0
produck-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dist/
|
produck-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 HasanCagriGungor
|
|
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.
|
produck-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: produck
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Satış Kiti API istemcisi, CLI ve MCP sunucusu: ürün linkinden rakip fiyatı, müşteri sesi ve listing metni.
|
|
5
|
+
Author: HasanCagriGungor
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: claude,ecommerce,hepsiburada,marketplace,mcp,sales-kit,trendyol
|
|
9
|
+
Classifier: Natural Language :: Turkish
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Office/Business
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Requires-Dist: httpx>=0.27
|
|
15
|
+
Provides-Extra: dev
|
|
16
|
+
Requires-Dist: build; extra == 'dev'
|
|
17
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
18
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
19
|
+
Requires-Dist: twine; extra == 'dev'
|
|
20
|
+
Provides-Extra: mcp
|
|
21
|
+
Requires-Dist: mcp<3,>=2.3; extra == 'mcp'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# produck
|
|
25
|
+
|
|
26
|
+
Satış Kiti API için Python istemcisi, komut satırı aracı ve MCP sunucusu.
|
|
27
|
+
Ürün linkini verin; rakip fiyatları, müşteri şikâyet/övgüleri, satın alma öncesi soruları ve satışa hazır listing metnini alın.
|
|
28
|
+
|
|
29
|
+
> PyPI'da `product` adı başka bir projeye ait olduğu için paket **`produck`** adıyla yayınlanır; içe aktarma adı `product`'tır.
|
|
30
|
+
|
|
31
|
+
## Kurulum
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install produck # istemci + CLI
|
|
35
|
+
pip install "produck[mcp]" # + MCP sunucusu
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Anahtarsız kullanım
|
|
39
|
+
|
|
40
|
+
API anahtarı vermeden de çalışır. produck.tr'de anahtarsız istekler saatlik limitle gerçek kit üretir; sunucu `DEMO_LIVE=false` ile çalışıyorsa ücretli servis çağrılmaz ve kayıtlı örnek kit döner (yanıtta `mode: "demo"`).
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from product import Product, summarize
|
|
44
|
+
|
|
45
|
+
p = Product() # varsayılan: https://produck.tr
|
|
46
|
+
print(summarize(p.sample(), p.base_url)) # örnek kit, maliyetsiz
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Canlı mod
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
p = Product(api_key="sk_live_...", base_url="https://produck.tr") # ya da PRODUCT_API_KEY
|
|
53
|
+
job = p.kit("https://www.hepsiburada.com/...", until="text") # ≈1-3 dk
|
|
54
|
+
print(summarize(job, p.base_url)["listing_copy"]["title"])
|
|
55
|
+
open("kit.pdf", "wb").write(p.pdf(job["id"]))
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Asenkron: `AsyncProduct` aynı yöntemleri `await` ile sunar.
|
|
59
|
+
|
|
60
|
+
## CLI
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
product sample
|
|
64
|
+
product --api-key sk_live_... kit "https://www.trendyol.com/..." --until done
|
|
65
|
+
product get <kit_id>
|
|
66
|
+
product pdf <kit_id> -o kit.pdf
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## MCP sunucusu
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
uvx --from "produck[mcp]" product-mcp # stdio, anahtarsız
|
|
73
|
+
PRODUCT_API_KEY=sk_live_... PRODUCT_API_URL=https://produck.tr uvx --from "produck[mcp]" product-mcp
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Araçlar: `create_sales_kit`, `get_sales_kit`, `sample_sales_kit`, `list_sales_kits`; istem: `sales_kit`.
|
|
77
|
+
|
|
78
|
+
Claude Desktop (`claude_desktop_config.json`):
|
|
79
|
+
|
|
80
|
+
```json
|
|
81
|
+
{
|
|
82
|
+
"mcpServers": {
|
|
83
|
+
"satis-kiti": {
|
|
84
|
+
"command": "uvx",
|
|
85
|
+
"args": ["--from", "produck[mcp]", "product-mcp"],
|
|
86
|
+
"env": { "PRODUCT_API_URL": "https://produck.tr", "PRODUCT_API_KEY": "" }
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Uzak sürüm `https://produck.tr/mcp` adresindedir; Claude'da (Ayarlar → Bağlayıcılar → Özel bağlayıcı ekle) ve ChatGPT'de (Eklentiler → Ekle → Özel MCP sunucusu ekle) URL ile eklenebilir. Kurulum: https://produck.tr/connect
|
produck-0.1.0/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# produck
|
|
2
|
+
|
|
3
|
+
Satış Kiti API için Python istemcisi, komut satırı aracı ve MCP sunucusu.
|
|
4
|
+
Ürün linkini verin; rakip fiyatları, müşteri şikâyet/övgüleri, satın alma öncesi soruları ve satışa hazır listing metnini alın.
|
|
5
|
+
|
|
6
|
+
> PyPI'da `product` adı başka bir projeye ait olduğu için paket **`produck`** adıyla yayınlanır; içe aktarma adı `product`'tır.
|
|
7
|
+
|
|
8
|
+
## Kurulum
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install produck # istemci + CLI
|
|
12
|
+
pip install "produck[mcp]" # + MCP sunucusu
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Anahtarsız kullanım
|
|
16
|
+
|
|
17
|
+
API anahtarı vermeden de çalışır. produck.tr'de anahtarsız istekler saatlik limitle gerçek kit üretir; sunucu `DEMO_LIVE=false` ile çalışıyorsa ücretli servis çağrılmaz ve kayıtlı örnek kit döner (yanıtta `mode: "demo"`).
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from product import Product, summarize
|
|
21
|
+
|
|
22
|
+
p = Product() # varsayılan: https://produck.tr
|
|
23
|
+
print(summarize(p.sample(), p.base_url)) # örnek kit, maliyetsiz
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Canlı mod
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
p = Product(api_key="sk_live_...", base_url="https://produck.tr") # ya da PRODUCT_API_KEY
|
|
30
|
+
job = p.kit("https://www.hepsiburada.com/...", until="text") # ≈1-3 dk
|
|
31
|
+
print(summarize(job, p.base_url)["listing_copy"]["title"])
|
|
32
|
+
open("kit.pdf", "wb").write(p.pdf(job["id"]))
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Asenkron: `AsyncProduct` aynı yöntemleri `await` ile sunar.
|
|
36
|
+
|
|
37
|
+
## CLI
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
product sample
|
|
41
|
+
product --api-key sk_live_... kit "https://www.trendyol.com/..." --until done
|
|
42
|
+
product get <kit_id>
|
|
43
|
+
product pdf <kit_id> -o kit.pdf
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## MCP sunucusu
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
uvx --from "produck[mcp]" product-mcp # stdio, anahtarsız
|
|
50
|
+
PRODUCT_API_KEY=sk_live_... PRODUCT_API_URL=https://produck.tr uvx --from "produck[mcp]" product-mcp
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Araçlar: `create_sales_kit`, `get_sales_kit`, `sample_sales_kit`, `list_sales_kits`; istem: `sales_kit`.
|
|
54
|
+
|
|
55
|
+
Claude Desktop (`claude_desktop_config.json`):
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{
|
|
59
|
+
"mcpServers": {
|
|
60
|
+
"satis-kiti": {
|
|
61
|
+
"command": "uvx",
|
|
62
|
+
"args": ["--from", "produck[mcp]", "product-mcp"],
|
|
63
|
+
"env": { "PRODUCT_API_URL": "https://produck.tr", "PRODUCT_API_KEY": "" }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Uzak sürüm `https://produck.tr/mcp` adresindedir; Claude'da (Ayarlar → Bağlayıcılar → Özel bağlayıcı ekle) ve ChatGPT'de (Eklentiler → Ekle → Özel MCP sunucusu ekle) URL ile eklenebilir. Kurulum: https://produck.tr/connect
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
# "product" adı PyPI'da başka bir projeye ait; dağıtım adı produck, import adı product.
|
|
7
|
+
name = "produck"
|
|
8
|
+
version = "0.1.0"
|
|
9
|
+
description = "Satış Kiti API istemcisi, CLI ve MCP sunucusu: ürün linkinden rakip fiyatı, müşteri sesi ve listing metni."
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
authors = [{ name = "HasanCagriGungor" }]
|
|
14
|
+
keywords = ["ecommerce", "marketplace", "sales-kit", "mcp", "claude", "trendyol", "hepsiburada"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
"Natural Language :: Turkish",
|
|
19
|
+
"Topic :: Office/Business",
|
|
20
|
+
]
|
|
21
|
+
dependencies = ["httpx>=0.27"]
|
|
22
|
+
|
|
23
|
+
[project.optional-dependencies]
|
|
24
|
+
mcp = ["mcp>=2.3,<3"]
|
|
25
|
+
dev = ["pytest>=8", "pytest-asyncio>=0.24", "build", "twine"]
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
product = "product.cli:main"
|
|
29
|
+
product-mcp = "product.mcp_server:main"
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.wheel]
|
|
32
|
+
packages = ["src/product"]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Satış Kiti API için Python istemcisi.
|
|
2
|
+
|
|
3
|
+
from product import Product
|
|
4
|
+
kit = Product().kit("https://www.hepsiburada.com/...") # anahtar yoksa demo modu
|
|
5
|
+
"""
|
|
6
|
+
from .client import (
|
|
7
|
+
DEFAULT_BASE_URL,
|
|
8
|
+
AsyncProduct,
|
|
9
|
+
Product,
|
|
10
|
+
ProductError,
|
|
11
|
+
summarize,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = ["Product", "AsyncProduct", "ProductError", "summarize", "DEFAULT_BASE_URL"]
|
|
15
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Komut satırı: product kit <url> | product get <id> | product sample | product pdf <id>"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .client import Product, ProductError, summarize
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _print(obj) -> None:
|
|
12
|
+
print(json.dumps(obj, ensure_ascii=False, indent=2))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(argv: list[str] | None = None) -> int:
|
|
16
|
+
p = argparse.ArgumentParser(prog="product", description="Satış Kiti API istemcisi")
|
|
17
|
+
p.add_argument("--api-key", default=None, help="yoksa PRODUCT_API_KEY; o da yoksa demo modu")
|
|
18
|
+
p.add_argument("--base-url", default=None, help="yoksa PRODUCT_API_URL")
|
|
19
|
+
p.add_argument("--raw", action="store_true", help="özet yerine ham JSON")
|
|
20
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
21
|
+
k = sub.add_parser("kit", help="ürün linkinden kit üret ve bekle")
|
|
22
|
+
k.add_argument("url")
|
|
23
|
+
k.add_argument("--until", choices=["text", "done"], default="text")
|
|
24
|
+
k.add_argument("--no-media", action="store_true")
|
|
25
|
+
k.add_argument("--no-wait", action="store_true")
|
|
26
|
+
g = sub.add_parser("get", help="kit durumunu getir")
|
|
27
|
+
g.add_argument("id")
|
|
28
|
+
sub.add_parser("sample", help="örnek kit (anahtar gerekmez)")
|
|
29
|
+
sub.add_parser("list", help="anahtarınızla oluşturulan kitler")
|
|
30
|
+
sub.add_parser("info", help="API bilgisi ve mod")
|
|
31
|
+
d = sub.add_parser("pdf", help="kiti PDF olarak indir")
|
|
32
|
+
d.add_argument("id")
|
|
33
|
+
d.add_argument("-o", "--out", default=None)
|
|
34
|
+
a = p.parse_args(argv)
|
|
35
|
+
|
|
36
|
+
out = (lambda j: _print(j)) if a.raw else None
|
|
37
|
+
with Product(a.api_key, a.base_url) as c:
|
|
38
|
+
show = out or (lambda j: _print(summarize(j, c.base_url)))
|
|
39
|
+
try:
|
|
40
|
+
if c.demo and a.cmd in ("kit", "sample"):
|
|
41
|
+
print("· demo modu (API anahtarı yok): örnek kit döner", file=sys.stderr)
|
|
42
|
+
if a.cmd == "kit":
|
|
43
|
+
job = c.create_kit(a.url, media=not a.no_media)
|
|
44
|
+
print(f"· başladı: {c.kit_url(job['id'])}", file=sys.stderr)
|
|
45
|
+
if not a.no_wait:
|
|
46
|
+
job = c.wait(job["id"], until=a.until,
|
|
47
|
+
on_event=lambda e: print(f" {e.get('stage')}", file=sys.stderr))
|
|
48
|
+
show(job)
|
|
49
|
+
elif a.cmd == "get":
|
|
50
|
+
show(c.get_kit(a.id))
|
|
51
|
+
elif a.cmd == "sample":
|
|
52
|
+
show(c.sample())
|
|
53
|
+
elif a.cmd == "list":
|
|
54
|
+
_print(c.list_kits())
|
|
55
|
+
elif a.cmd == "info":
|
|
56
|
+
_print(c.info())
|
|
57
|
+
elif a.cmd == "pdf":
|
|
58
|
+
path = a.out or f"satis-kiti-{a.id}.pdf"
|
|
59
|
+
with open(path, "wb") as f:
|
|
60
|
+
f.write(c.pdf(a.id))
|
|
61
|
+
print(path)
|
|
62
|
+
except ProductError as e:
|
|
63
|
+
print(f"Hata {e.status}: {e.message}", file=sys.stderr)
|
|
64
|
+
return 1
|
|
65
|
+
except TimeoutError as e:
|
|
66
|
+
print(str(e), file=sys.stderr)
|
|
67
|
+
return 2
|
|
68
|
+
return 0
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
if __name__ == "__main__":
|
|
72
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Senkron ve asenkron HTTP istemcisi.
|
|
2
|
+
|
|
3
|
+
Anahtar verilmezse (ve PRODUCT_API_KEY tanımlı değilse) istekler demo modunda gider:
|
|
4
|
+
sunucu örnek bir Satış Kiti döndürür, ücretli hiçbir servis çağrılmaz.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
DEFAULT_BASE_URL = "https://produck.tr"
|
|
16
|
+
DONE = ("done", "failed")
|
|
17
|
+
TEXT_READY = ("text_ready", "done", "failed")
|
|
18
|
+
|
|
19
|
+
EventHook = Callable[[dict], None]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ProductError(Exception):
|
|
23
|
+
def __init__(self, status: int, message: str):
|
|
24
|
+
super().__init__(f"{status}: {message}")
|
|
25
|
+
self.status = status
|
|
26
|
+
self.message = message
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _config(api_key: str | None, base_url: str | None) -> tuple[str | None, str]:
|
|
30
|
+
key = api_key if api_key is not None else os.environ.get("PRODUCT_API_KEY") or None
|
|
31
|
+
url = (base_url or os.environ.get("PRODUCT_API_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
32
|
+
return key, url
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _headers(api_key: str | None, extra: dict | None) -> dict:
|
|
36
|
+
h = {"User-Agent": "produck-python/0.1", "Accept": "application/json"}
|
|
37
|
+
if api_key:
|
|
38
|
+
h["Authorization"] = f"Bearer {api_key}"
|
|
39
|
+
h.update(extra or {})
|
|
40
|
+
return h
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _raise_for(r: httpx.Response) -> None:
|
|
44
|
+
if r.is_success:
|
|
45
|
+
return
|
|
46
|
+
try:
|
|
47
|
+
msg = r.json().get("detail") or r.text
|
|
48
|
+
except ValueError:
|
|
49
|
+
msg = r.text
|
|
50
|
+
raise ProductError(r.status_code, str(msg))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _targets(until: str) -> tuple[str, ...]:
|
|
54
|
+
if until not in ("text", "done"):
|
|
55
|
+
raise ValueError("until 'text' ya da 'done' olmalı")
|
|
56
|
+
return TEXT_READY if until == "text" else DONE
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Product:
|
|
60
|
+
"""Senkron istemci.
|
|
61
|
+
|
|
62
|
+
>>> p = Product() # demo modu
|
|
63
|
+
>>> p = Product(api_key="sk_...") # canlı mod
|
|
64
|
+
>>> kit = p.kit("https://...") # başlat + metin hazır olana kadar bekle
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(self, api_key: str | None = None, base_url: str | None = None, *,
|
|
68
|
+
timeout: float = 60, transport: httpx.BaseTransport | None = None, headers: dict | None = None):
|
|
69
|
+
self.api_key, self.base_url = _config(api_key, base_url)
|
|
70
|
+
self._http = httpx.Client(base_url=self.base_url, timeout=timeout, transport=transport,
|
|
71
|
+
headers=_headers(self.api_key, headers), follow_redirects=True)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def demo(self) -> bool:
|
|
75
|
+
return not self.api_key
|
|
76
|
+
|
|
77
|
+
def _req(self, method: str, path: str, **kw) -> httpx.Response:
|
|
78
|
+
r = self._http.request(method, path, **kw)
|
|
79
|
+
_raise_for(r)
|
|
80
|
+
return r
|
|
81
|
+
|
|
82
|
+
def info(self) -> dict:
|
|
83
|
+
return self._req("GET", "/v1").json()
|
|
84
|
+
|
|
85
|
+
def create_kit(self, url: str, media: bool = True) -> dict:
|
|
86
|
+
"""İşi başlatır, hemen döner: {id, status, kit_url, mode}."""
|
|
87
|
+
return self._req("POST", "/v1/kits", json={"url": url, "media": media}).json()
|
|
88
|
+
|
|
89
|
+
def get_kit(self, kit_id: str, since: int = 0) -> dict:
|
|
90
|
+
return self._req("GET", f"/v1/kits/{kit_id}", params={"since": since}).json()
|
|
91
|
+
|
|
92
|
+
def list_kits(self, limit: int = 20) -> list[dict]:
|
|
93
|
+
return self._req("GET", "/v1/kits", params={"limit": limit}).json()["kits"]
|
|
94
|
+
|
|
95
|
+
def sample(self) -> dict:
|
|
96
|
+
"""Örnek kit (anahtar gerekmez, maliyetsiz)."""
|
|
97
|
+
return self._req("GET", "/v1/demo").json()
|
|
98
|
+
|
|
99
|
+
def pdf(self, kit_id: str) -> bytes:
|
|
100
|
+
return self._req("GET", f"/v1/kits/{kit_id}/pdf", timeout=120).content
|
|
101
|
+
|
|
102
|
+
def kit_url(self, kit_id: str) -> str:
|
|
103
|
+
return f"{self.base_url}/kit/{kit_id}"
|
|
104
|
+
|
|
105
|
+
def wait(self, kit_id: str, until: str = "text", timeout: float = 600, poll: float = 3,
|
|
106
|
+
on_event: EventHook | None = None) -> dict:
|
|
107
|
+
"""until='text': metin kiti hazır (≈1-2 dk). until='done': görsel ve video da hazır."""
|
|
108
|
+
targets, since, deadline = _targets(until), 0, time.monotonic() + timeout
|
|
109
|
+
while True:
|
|
110
|
+
job = self.get_kit(kit_id, since)
|
|
111
|
+
for ev in job.get("events") or []:
|
|
112
|
+
if on_event:
|
|
113
|
+
on_event(ev)
|
|
114
|
+
since = job.get("next", since)
|
|
115
|
+
if job["status"] in targets:
|
|
116
|
+
return job
|
|
117
|
+
if time.monotonic() > deadline:
|
|
118
|
+
raise TimeoutError(f"Kit {kit_id} {timeout:.0f} sn içinde hazır olmadı (durum: {job['status']}).")
|
|
119
|
+
time.sleep(poll)
|
|
120
|
+
|
|
121
|
+
def kit(self, url: str, until: str = "text", media: bool = True, **wait_kw) -> dict:
|
|
122
|
+
job = self.create_kit(url, media=media)
|
|
123
|
+
return self.wait(job["id"], until=until, **wait_kw)
|
|
124
|
+
|
|
125
|
+
def close(self) -> None:
|
|
126
|
+
self._http.close()
|
|
127
|
+
|
|
128
|
+
def __enter__(self):
|
|
129
|
+
return self
|
|
130
|
+
|
|
131
|
+
def __exit__(self, *exc):
|
|
132
|
+
self.close()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class AsyncProduct:
|
|
136
|
+
"""Asenkron istemci, Product ile aynı yöntemler (await ile)."""
|
|
137
|
+
|
|
138
|
+
def __init__(self, api_key: str | None = None, base_url: str | None = None, *,
|
|
139
|
+
timeout: float = 60, transport: httpx.AsyncBaseTransport | None = None, headers: dict | None = None):
|
|
140
|
+
self.api_key, self.base_url = _config(api_key, base_url)
|
|
141
|
+
self._http = httpx.AsyncClient(base_url=self.base_url, timeout=timeout, transport=transport,
|
|
142
|
+
headers=_headers(self.api_key, headers), follow_redirects=True)
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def demo(self) -> bool:
|
|
146
|
+
return not self.api_key
|
|
147
|
+
|
|
148
|
+
async def _req(self, method: str, path: str, **kw) -> httpx.Response:
|
|
149
|
+
r = await self._http.request(method, path, **kw)
|
|
150
|
+
_raise_for(r)
|
|
151
|
+
return r
|
|
152
|
+
|
|
153
|
+
async def info(self) -> dict:
|
|
154
|
+
return (await self._req("GET", "/v1")).json()
|
|
155
|
+
|
|
156
|
+
async def create_kit(self, url: str, media: bool = True) -> dict:
|
|
157
|
+
return (await self._req("POST", "/v1/kits", json={"url": url, "media": media})).json()
|
|
158
|
+
|
|
159
|
+
async def get_kit(self, kit_id: str, since: int = 0) -> dict:
|
|
160
|
+
return (await self._req("GET", f"/v1/kits/{kit_id}", params={"since": since})).json()
|
|
161
|
+
|
|
162
|
+
async def list_kits(self, limit: int = 20) -> list[dict]:
|
|
163
|
+
return (await self._req("GET", "/v1/kits", params={"limit": limit})).json()["kits"]
|
|
164
|
+
|
|
165
|
+
async def sample(self) -> dict:
|
|
166
|
+
return (await self._req("GET", "/v1/demo")).json()
|
|
167
|
+
|
|
168
|
+
async def pdf(self, kit_id: str) -> bytes:
|
|
169
|
+
return (await self._req("GET", f"/v1/kits/{kit_id}/pdf", timeout=120)).content
|
|
170
|
+
|
|
171
|
+
def kit_url(self, kit_id: str) -> str:
|
|
172
|
+
return f"{self.base_url}/kit/{kit_id}"
|
|
173
|
+
|
|
174
|
+
async def wait(self, kit_id: str, until: str = "text", timeout: float = 600, poll: float = 3,
|
|
175
|
+
on_event: EventHook | None = None) -> dict:
|
|
176
|
+
targets, since, deadline = _targets(until), 0, time.monotonic() + timeout
|
|
177
|
+
while True:
|
|
178
|
+
job = await self.get_kit(kit_id, since)
|
|
179
|
+
for ev in job.get("events") or []:
|
|
180
|
+
if on_event:
|
|
181
|
+
on_event(ev)
|
|
182
|
+
since = job.get("next", since)
|
|
183
|
+
if job["status"] in targets:
|
|
184
|
+
return job
|
|
185
|
+
if time.monotonic() > deadline:
|
|
186
|
+
raise TimeoutError(f"Kit {kit_id} {timeout:.0f} sn içinde hazır olmadı (durum: {job['status']}).")
|
|
187
|
+
await asyncio.sleep(poll)
|
|
188
|
+
|
|
189
|
+
async def kit(self, url: str, until: str = "text", media: bool = True, **wait_kw) -> dict:
|
|
190
|
+
job = await self.create_kit(url, media=media)
|
|
191
|
+
return await self.wait(job["id"], until=until, **wait_kw)
|
|
192
|
+
|
|
193
|
+
async def aclose(self) -> None:
|
|
194
|
+
await self._http.aclose()
|
|
195
|
+
|
|
196
|
+
async def __aenter__(self):
|
|
197
|
+
return self
|
|
198
|
+
|
|
199
|
+
async def __aexit__(self, *exc):
|
|
200
|
+
await self.aclose()
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# ---------- LLM/CLI için kısa özet (ham sonuç ~30 KB) ----------
|
|
204
|
+
|
|
205
|
+
def _pick(d: dict | None, *keys: str) -> dict:
|
|
206
|
+
d = d or {}
|
|
207
|
+
return {k: d[k] for k in keys if d.get(k) not in (None, "", [], {})}
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def summarize(job: dict, base_url: str | None = None) -> dict[str, Any]:
|
|
211
|
+
"""GET /v1/kits/{id} yanıtını sohbet/CLI için okunur bir özete indirger."""
|
|
212
|
+
res = job.get("result") or {}
|
|
213
|
+
ins = res.get("insights") or {}
|
|
214
|
+
media = res.get("media") or {}
|
|
215
|
+
out: dict[str, Any] = {
|
|
216
|
+
"id": job.get("id"),
|
|
217
|
+
"status": job.get("status"),
|
|
218
|
+
"mode": job.get("mode"),
|
|
219
|
+
}
|
|
220
|
+
if base_url and job.get("id"):
|
|
221
|
+
out["kit_url"] = f"{base_url.rstrip('/')}/kit/{job['id']}"
|
|
222
|
+
out["pdf_url"] = f"{base_url.rstrip('/')}/kit/{job['id']}/pdf"
|
|
223
|
+
if job.get("error"):
|
|
224
|
+
out["error"] = job["error"]
|
|
225
|
+
if not res:
|
|
226
|
+
return out
|
|
227
|
+
out["product"] = _pick(res.get("product"), "name", "brand", "price", "currency", "in_stock", "rating", "review_count")
|
|
228
|
+
out["category"] = res.get("category")
|
|
229
|
+
out["price_position"] = res.get("price_position")
|
|
230
|
+
out["market"] = [
|
|
231
|
+
_pick(m, "site", "seller", "price", "in_stock", "url") for m in (res.get("market") or [])
|
|
232
|
+
if not m.get("outlier")
|
|
233
|
+
][:8]
|
|
234
|
+
out["competitors"] = [
|
|
235
|
+
_pick(c, "name", "price", "advantage", "disadvantage", "url") for c in (res.get("competitors") or [])
|
|
236
|
+
][:5]
|
|
237
|
+
out["summary"] = ins.get("summary")
|
|
238
|
+
out["market_insight"] = ins.get("market_insight")
|
|
239
|
+
out["praises"] = [_pick(p, "title", "detail", "mentions", "quote") for p in ins.get("praises") or []]
|
|
240
|
+
out["complaints"] = [_pick(p, "title", "detail", "mentions", "quote") for p in ins.get("complaints") or []]
|
|
241
|
+
out["pre_purchase_questions"] = [_pick(q, "question", "answer") for q in ins.get("pre_purchase_questions") or []]
|
|
242
|
+
out["listing_copy"] = ins.get("copy")
|
|
243
|
+
out["media"] = {
|
|
244
|
+
"image": (media.get("image") or {}).get("url"),
|
|
245
|
+
"video": (media.get("video") or {}).get("url"),
|
|
246
|
+
}
|
|
247
|
+
out["sources"] = [v.get("url") for v in res.get("voice_sources") or [] if v.get("url")][:10]
|
|
248
|
+
return {k: v for k, v in out.items() if v not in (None, "", [], {})}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Satış Kiti MCP sunucusu.
|
|
2
|
+
|
|
3
|
+
Yerel (stdio), Claude Desktop / Claude Code için:
|
|
4
|
+
uvx --from "produck[mcp]" product-mcp
|
|
5
|
+
PRODUCT_API_KEY=sk_... PRODUCT_API_URL=https://... product-mcp
|
|
6
|
+
|
|
7
|
+
Uzak (HTTP) sürüm Satış Kiti sunucusunun /mcp adresinde aynı araçlarla çalışır
|
|
8
|
+
(bkz. app/mcp_remote.py); claude.ai'de "custom connector" olarak eklenir.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import asyncio
|
|
14
|
+
import json
|
|
15
|
+
import time
|
|
16
|
+
from contextlib import AbstractAsyncContextManager, asynccontextmanager
|
|
17
|
+
from typing import Callable
|
|
18
|
+
|
|
19
|
+
from .client import AsyncProduct, ProductError, TEXT_READY, summarize
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
23
|
+
from mcp.types import ToolAnnotations
|
|
24
|
+
except ImportError as e: # pragma: no cover
|
|
25
|
+
raise SystemExit("MCP için: pip install 'produck[mcp]'") from e
|
|
26
|
+
|
|
27
|
+
# ctx -> async with ... as (client, public_base_url)
|
|
28
|
+
ClientFactory = Callable[[Context | None], AbstractAsyncContextManager[tuple[AsyncProduct, str]]]
|
|
29
|
+
|
|
30
|
+
INSTRUCTIONS = """\
|
|
31
|
+
Satış Kiti (Produck) turns a marketplace product link (Hepsiburada, Trendyol, Amazon TR, n11 …) into a
|
|
32
|
+
sales kit for small sellers: competitor prices and price position, customer praise and complaints from
|
|
33
|
+
reviews, pre-purchase questions and ready-to-use listing copy (title and description). Output is in Turkish.
|
|
34
|
+
|
|
35
|
+
A text kit takes about 1-3 minutes. create_sales_kit returns the kit id and, if it is not ready within the
|
|
36
|
+
wait time, status "running"; get_sales_kit returns the same kit once it is ready. Results with
|
|
37
|
+
mode "demo" are a stored sample kit, not an analysis of the given link.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
# Cloudflare gibi vekiller isteği ~100 sn'de keser; kalanı get_sales_kit ile sorulur
|
|
41
|
+
MAX_WAIT = 80
|
|
42
|
+
|
|
43
|
+
def _ro(title: str) -> ToolAnnotations:
|
|
44
|
+
return ToolAnnotations(title=title, read_only_hint=True, open_world_hint=False)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _dump(obj) -> str:
|
|
48
|
+
return json.dumps(obj, ensure_ascii=False, indent=1)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def build_server(client_for: ClientFactory, name: str = "satis-kiti") -> MCPServer:
|
|
52
|
+
mcp = MCPServer(name=name, title="Satış Kiti", instructions=INSTRUCTIONS, version="0.1.0")
|
|
53
|
+
|
|
54
|
+
async def _wait(client: AsyncProduct, kit_id: str, budget: float, ctx: Context | None) -> dict:
|
|
55
|
+
deadline, since = time.monotonic() + budget, 0
|
|
56
|
+
while True:
|
|
57
|
+
job = await client.get_kit(kit_id, since)
|
|
58
|
+
since = job.get("next", since)
|
|
59
|
+
evs = job.get("events") or []
|
|
60
|
+
if ctx and evs:
|
|
61
|
+
try:
|
|
62
|
+
await ctx.report_progress(since, None, evs[-1].get("stage"))
|
|
63
|
+
except Exception:
|
|
64
|
+
pass
|
|
65
|
+
if job["status"] in TEXT_READY or time.monotonic() > deadline:
|
|
66
|
+
return job
|
|
67
|
+
await asyncio.sleep(3)
|
|
68
|
+
|
|
69
|
+
def _with_hint(s: dict) -> str:
|
|
70
|
+
if s.get("status") not in ("done", "failed", "text_ready"):
|
|
71
|
+
s["pending"] = f"Kit is still being prepared; get_sales_kit(kit_id='{s['id']}') returns it when ready."
|
|
72
|
+
if s.get("mode") == "demo":
|
|
73
|
+
s["demo_notice"] = "Sample kit: the given link was not analyzed. Analyzing your own products needs an API key."
|
|
74
|
+
s.pop("media", None) # bağlayıcı yapay zekâ görseli/videosu üretmez
|
|
75
|
+
return _dump(s)
|
|
76
|
+
|
|
77
|
+
@mcp.tool(title="Create sales kit",
|
|
78
|
+
annotations=ToolAnnotations(title="Create sales kit", read_only_hint=False,
|
|
79
|
+
destructive_hint=False, open_world_hint=True))
|
|
80
|
+
async def create_sales_kit(ctx: Context, url: str, wait_seconds: int = 75) -> str:
|
|
81
|
+
"""Analyze a marketplace product page URL and build a text sales kit: seller prices and price position,
|
|
82
|
+
competitor products, customer praise/complaints from reviews, pre-purchase questions and listing copy.
|
|
83
|
+
Waits up to wait_seconds (max 80) for the result; otherwise returns the kit id with status "running".
|
|
84
|
+
Uses the Produck Sales Kit API (POST /v1/kits, docs: https://produck.tr/docs)."""
|
|
85
|
+
async with client_for(ctx) as (client, base):
|
|
86
|
+
try:
|
|
87
|
+
started = await client.create_kit(url, media=False)
|
|
88
|
+
job = await _wait(client, started["id"], max(0, min(wait_seconds, MAX_WAIT)), ctx)
|
|
89
|
+
except ProductError as e:
|
|
90
|
+
return _dump({"error": e.message, "status": e.status})
|
|
91
|
+
job.setdefault("mode", started.get("mode"))
|
|
92
|
+
return _with_hint(summarize(job, base))
|
|
93
|
+
|
|
94
|
+
@mcp.tool(title="Get sales kit", annotations=_ro("Get sales kit"))
|
|
95
|
+
async def get_sales_kit(ctx: Context, kit_id: str) -> str:
|
|
96
|
+
"""Return the status and, when ready, the summary of a sales kit by its id (from create_sales_kit)."""
|
|
97
|
+
async with client_for(ctx) as (client, base):
|
|
98
|
+
try:
|
|
99
|
+
job = await client.get_kit(kit_id)
|
|
100
|
+
except ProductError as e:
|
|
101
|
+
return _dump({"error": e.message, "status": e.status})
|
|
102
|
+
return _with_hint(summarize(job, base))
|
|
103
|
+
|
|
104
|
+
@mcp.tool(title="Sample sales kit", annotations=_ro("Sample sales kit"))
|
|
105
|
+
async def sample_sales_kit(ctx: Context) -> str:
|
|
106
|
+
"""Return a stored example sales kit (a Stanley thermos on Hepsiburada) that shows what a kit contains."""
|
|
107
|
+
async with client_for(ctx) as (client, base):
|
|
108
|
+
return _with_hint(summarize(await client.sample(), base))
|
|
109
|
+
|
|
110
|
+
@mcp.tool(title="List my sales kits", annotations=_ro("List my sales kits"))
|
|
111
|
+
async def list_sales_kits(ctx: Context, limit: int = 10) -> str:
|
|
112
|
+
"""List recent sales kits created with your API key (empty without an API key)."""
|
|
113
|
+
async with client_for(ctx) as (client, base):
|
|
114
|
+
try:
|
|
115
|
+
kits = await client.list_kits(limit)
|
|
116
|
+
except ProductError as e:
|
|
117
|
+
return _dump({"error": e.message, "status": e.status})
|
|
118
|
+
for k in kits:
|
|
119
|
+
k["kit_url"] = f"{base}/kit/{k['id']}"
|
|
120
|
+
return _dump(kits)
|
|
121
|
+
|
|
122
|
+
@mcp.prompt(title="Sales kit from a product link")
|
|
123
|
+
def sales_kit(url: str) -> str:
|
|
124
|
+
"""Bir ürün linki için Satış Kiti çıkarıp yorumlar."""
|
|
125
|
+
return (f"{url} için create_sales_kit aracıyla Satış Kiti oluştur. Sonra: 1) fiyat konumunu ve "
|
|
126
|
+
"fiyat önerisini, 2) en sık 3 şikâyeti ve listing'de nasıl karşılanacağını, 3) önerilen başlık "
|
|
127
|
+
"ve kısa açıklamayı Türkçe, kısa maddelerle yaz. Kit linkini en sona ekle.")
|
|
128
|
+
|
|
129
|
+
return mcp
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def local_factory(api_key: str | None = None, base_url: str | None = None) -> ClientFactory:
|
|
133
|
+
"""stdio için: tek, uzun ömürlü istemci."""
|
|
134
|
+
client = AsyncProduct(api_key, base_url)
|
|
135
|
+
|
|
136
|
+
@asynccontextmanager
|
|
137
|
+
async def factory(_ctx):
|
|
138
|
+
yield client, client.base_url
|
|
139
|
+
|
|
140
|
+
return factory
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def main(argv: list[str] | None = None) -> None:
|
|
144
|
+
p = argparse.ArgumentParser(prog="product-mcp", description="Satış Kiti MCP sunucusu")
|
|
145
|
+
p.add_argument("--api-key", default=None, help="yoksa PRODUCT_API_KEY; o da yoksa demo modu")
|
|
146
|
+
p.add_argument("--base-url", default=None, help="yoksa PRODUCT_API_URL")
|
|
147
|
+
p.add_argument("--transport", choices=["stdio", "streamable-http"], default="stdio")
|
|
148
|
+
p.add_argument("--port", type=int, default=8765)
|
|
149
|
+
a = p.parse_args(argv)
|
|
150
|
+
server = build_server(local_factory(a.api_key, a.base_url))
|
|
151
|
+
if a.transport == "stdio":
|
|
152
|
+
server.run("stdio")
|
|
153
|
+
else:
|
|
154
|
+
server.run("streamable-http", port=a.port)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == "__main__":
|
|
158
|
+
main()
|