ownapi 1.0.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.
- cli.py +1017 -0
- compiler.py +948 -0
- core/__init__.py +19 -0
- core/api_keys.py +523 -0
- core/auto_repair.py +682 -0
- core/base_client.py +165 -0
- core/consent.py +169 -0
- core/form_automation.py +1044 -0
- core/hitl_queue.py +886 -0
- core/onboarding.py +1457 -0
- core/token_store.py +223 -0
- healer.py +2074 -0
- master_mcp.py +193 -0
- ownapi/__init__.py +94 -0
- ownapi/cli.py +309 -0
- ownapi/sdk.py +436 -0
- ownapi-1.0.0.dist-info/METADATA +287 -0
- ownapi-1.0.0.dist-info/RECORD +62 -0
- ownapi-1.0.0.dist-info/WHEEL +5 -0
- ownapi-1.0.0.dist-info/entry_points.txt +4 -0
- ownapi-1.0.0.dist-info/top_level.txt +10 -0
- recorder.py +486 -0
- registry/coingecko/__init__.py +5 -0
- registry/coingecko/client.py +84 -0
- registry/coingecko/schema.json +23 -0
- registry/edevlet/__init__.py +5 -0
- registry/edevlet/client.py +54 -0
- registry/edevlet/schema.json +14 -0
- registry/enuygun/__init__.py +5 -0
- registry/enuygun/client.py +78 -0
- registry/enuygun/schema.json +13 -0
- registry/github_trending/__init__.py +5 -0
- registry/github_trending/client.py +90 -0
- registry/github_trending/schema.json +31 -0
- registry/hackernews/__init__.py +5 -0
- registry/hackernews/client.py +90 -0
- registry/hackernews/schema.json +38 -0
- registry/hepsiburada/__init__.py +5 -0
- registry/hepsiburada/client.py +32 -0
- registry/hepsiburada/schema.json +23 -0
- registry/linkedin_jobs/__init__.py +5 -0
- registry/linkedin_jobs/client.py +241 -0
- registry/linkedin_jobs/schema.json +46 -0
- registry/pegasus/__init__.py +5 -0
- registry/pegasus/client.py +141 -0
- registry/pegasus/schema.json +76 -0
- registry/thy/__init__.py +5 -0
- registry/thy/client.py +1796 -0
- registry/thy/schema.json +46 -0
- registry/trendyol/__init__.py +5 -0
- registry/trendyol/client.py +228 -0
- registry/trendyol/schema.json +30 -0
- registry/ucak_bileti/client.py +94 -0
- registry/ucak_bileti/schema.json +47 -0
- registry/wikipedia/__init__.py +5 -0
- registry/wikipedia/client.py +64 -0
- registry/wikipedia/schema.json +31 -0
- registry/yahoo_finance/__init__.py +5 -0
- registry/yahoo_finance/client.py +98 -0
- registry/yahoo_finance/schema.json +22 -0
- server.py +891 -0
- static/index.html +2401 -0
master_mcp.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import builtins
|
|
4
|
+
import contextlib
|
|
5
|
+
import functools
|
|
6
|
+
import importlib.util
|
|
7
|
+
import inspect
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
|
|
13
|
+
# MCP stdio protokolünde JSON-RPC akışının bozulmaması ("Connection closed" hatası almamak) için
|
|
14
|
+
# interaktif input() beklemelerini kapat ve varsayılan print() çağrılarını sys.stderr'e yönlendir.
|
|
15
|
+
if "--check" not in sys.argv:
|
|
16
|
+
os.environ["OWNAPI_NON_INTERACTIVE"] = "1"
|
|
17
|
+
_orig_print = builtins.print
|
|
18
|
+
|
|
19
|
+
def _stderr_print(*args: Any, **kwargs: Any) -> None:
|
|
20
|
+
if "file" not in kwargs or kwargs["file"] is None or kwargs["file"] is sys.stdout:
|
|
21
|
+
kwargs["file"] = sys.stderr
|
|
22
|
+
_orig_print(*args, **kwargs)
|
|
23
|
+
|
|
24
|
+
builtins.print = _stderr_print
|
|
25
|
+
|
|
26
|
+
from mcp.server.fastmcp import FastMCP
|
|
27
|
+
|
|
28
|
+
# Proje kök dizinini sys.path'e ekle (healer, compiler vb. modüllerin bulunabilmesi için)
|
|
29
|
+
PROJECT_ROOT = Path(__file__).resolve().parent
|
|
30
|
+
if str(PROJECT_ROOT) not in sys.path:
|
|
31
|
+
sys.path.insert(0, str(PROJECT_ROOT))
|
|
32
|
+
|
|
33
|
+
from compiler import RegistrySchema, ensure_default_registry
|
|
34
|
+
|
|
35
|
+
mcp = FastMCP("OwnAPI Master Registry")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _wrap_tool_with_stderr_redirect(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
39
|
+
"""
|
|
40
|
+
MCP aracı çalışırken alt modüllerden (`healer`, `client.py` vb.) gelebilecek tüm
|
|
41
|
+
`sys.stdout` çıktılarını `sys.stderr` kanalına yönlendirerek JSON-RPC `stdio` hattını korur.
|
|
42
|
+
Ayrıca WAF/Captcha engeline takılan ajan görevlerinin öldürülmek yerine `.sessions/hitl_state.json`
|
|
43
|
+
üzerinden 'PAUSED' durumuna alınıp kullanıcı onayından sonra kaldığı yerden ('resume')
|
|
44
|
+
devam etmesini garanti altına alır.
|
|
45
|
+
"""
|
|
46
|
+
if inspect.iscoroutinefunction(fn):
|
|
47
|
+
@functools.wraps(fn)
|
|
48
|
+
async def _async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
49
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
50
|
+
os.environ.setdefault("OWNAPI_HITL_PAUSE_AND_WAIT", "1")
|
|
51
|
+
result = await fn(*args, **kwargs)
|
|
52
|
+
if isinstance(result, dict) and result.get("status") in ("PAUSED", "PENDING_USER_APPROVAL", "PENDING_USER_ACTION") and result.get("task_id"):
|
|
53
|
+
from core.hitl_queue import HITLQueueManager
|
|
54
|
+
|
|
55
|
+
mgr = HITLQueueManager()
|
|
56
|
+
resumed = await mgr.await_task_resume(
|
|
57
|
+
str(result["task_id"]),
|
|
58
|
+
poll_interval=0.5,
|
|
59
|
+
timeout_sec=float(os.getenv("OWNAPI_HITL_PAUSE_TIMEOUT", "300")),
|
|
60
|
+
)
|
|
61
|
+
if resumed is not None:
|
|
62
|
+
if resumed.get("response") is not None:
|
|
63
|
+
return resumed["response"]
|
|
64
|
+
return await fn(*args, **kwargs)
|
|
65
|
+
return result
|
|
66
|
+
|
|
67
|
+
_async_wrapper.__signature__ = inspect.signature(fn) # type: ignore[attr-defined]
|
|
68
|
+
return _async_wrapper
|
|
69
|
+
|
|
70
|
+
@functools.wraps(fn)
|
|
71
|
+
def _sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
72
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
73
|
+
os.environ.setdefault("OWNAPI_HITL_PAUSE_AND_WAIT", "1")
|
|
74
|
+
result = fn(*args, **kwargs)
|
|
75
|
+
if isinstance(result, dict) and result.get("status") in ("PAUSED", "PENDING_USER_APPROVAL", "PENDING_USER_ACTION") and result.get("task_id"):
|
|
76
|
+
import asyncio
|
|
77
|
+
from core.hitl_queue import HITLQueueManager
|
|
78
|
+
|
|
79
|
+
mgr = HITLQueueManager()
|
|
80
|
+
resumed = asyncio.run(
|
|
81
|
+
mgr.await_task_resume(
|
|
82
|
+
str(result["task_id"]),
|
|
83
|
+
poll_interval=0.5,
|
|
84
|
+
timeout_sec=float(os.getenv("OWNAPI_HITL_PAUSE_TIMEOUT", "300")),
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
if resumed is not None:
|
|
88
|
+
if resumed.get("response") is not None:
|
|
89
|
+
return resumed["response"]
|
|
90
|
+
return fn(*args, **kwargs)
|
|
91
|
+
return result
|
|
92
|
+
|
|
93
|
+
_sync_wrapper.__signature__ = inspect.signature(fn) # type: ignore[attr-defined]
|
|
94
|
+
return _sync_wrapper
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def load_registry_tools(registry_root: Path = PROJECT_ROOT / "registry") -> list[tuple[RegistrySchema, Callable[..., Any]]]:
|
|
98
|
+
"""
|
|
99
|
+
registry/ klasöründeki tüm derlenmiş client.py modüllerini ve schema.json dosyalarını
|
|
100
|
+
dinamik olarak içe aktarır.
|
|
101
|
+
"""
|
|
102
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
103
|
+
ensure_default_registry(registry_root)
|
|
104
|
+
loaded_tools: list[tuple[RegistrySchema, Callable[..., Any]]] = []
|
|
105
|
+
|
|
106
|
+
if not registry_root.exists():
|
|
107
|
+
return loaded_tools
|
|
108
|
+
|
|
109
|
+
for service_dir in sorted(registry_root.iterdir()):
|
|
110
|
+
if not service_dir.is_dir():
|
|
111
|
+
continue
|
|
112
|
+
|
|
113
|
+
schema_path = service_dir / "schema.json"
|
|
114
|
+
client_path = service_dir / "client.py"
|
|
115
|
+
if not schema_path.exists() or not client_path.exists():
|
|
116
|
+
continue
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
schema = RegistrySchema.model_validate_json(schema_path.read_text(encoding="utf-8"))
|
|
120
|
+
module_name = f"shadow_registry_{schema.service_name}"
|
|
121
|
+
spec = importlib.util.spec_from_file_location(module_name, str(client_path.resolve()))
|
|
122
|
+
if spec is None or spec.loader is None:
|
|
123
|
+
continue
|
|
124
|
+
|
|
125
|
+
module = importlib.util.module_from_spec(spec)
|
|
126
|
+
sys.modules[module_name] = module
|
|
127
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
128
|
+
spec.loader.exec_module(module)
|
|
129
|
+
|
|
130
|
+
fn = getattr(module, schema.function_name, None)
|
|
131
|
+
if fn is None or not callable(fn):
|
|
132
|
+
# İsim eşleşmezse modüldeki ilk genel fonksiyonu al
|
|
133
|
+
candidates = [
|
|
134
|
+
obj
|
|
135
|
+
for name, obj in inspect.getmembers(module, inspect.isfunction)
|
|
136
|
+
if obj.__module__ == module_name and not name.startswith("_")
|
|
137
|
+
]
|
|
138
|
+
if not candidates:
|
|
139
|
+
continue
|
|
140
|
+
fn = candidates[0]
|
|
141
|
+
|
|
142
|
+
loaded_tools.append((schema, _wrap_tool_with_stderr_redirect(fn)))
|
|
143
|
+
except Exception as exc:
|
|
144
|
+
sys.stderr.write(f"[OwnAPI Master MCP] {service_dir.name} yüklenirken uyarı: {exc}\n")
|
|
145
|
+
|
|
146
|
+
return loaded_tools
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def register_all_tools() -> list[RegistrySchema]:
|
|
150
|
+
"""Yüklenen tüm OwnAPI Registry fonksiyonlarını tek bir FastMCP sunucusuna @mcp.tool() olarak kaydeder."""
|
|
151
|
+
tools = load_registry_tools()
|
|
152
|
+
registered_schemas: list[RegistrySchema] = []
|
|
153
|
+
used_tool_names: set[str] = set()
|
|
154
|
+
|
|
155
|
+
for schema, fn in tools:
|
|
156
|
+
tool_name = schema.function_name
|
|
157
|
+
if tool_name in used_tool_names:
|
|
158
|
+
tool_name = f"{schema.service_name}_{schema.function_name}"
|
|
159
|
+
used_tool_names.add(tool_name)
|
|
160
|
+
|
|
161
|
+
description = (
|
|
162
|
+
f"[{schema.service_name}] {schema.explanation} "
|
|
163
|
+
f"(Endpoint: {schema.method} {schema.endpoint_url})"
|
|
164
|
+
)
|
|
165
|
+
mcp.tool(name=tool_name, description=description)(fn)
|
|
166
|
+
registered_schemas.append(schema)
|
|
167
|
+
|
|
168
|
+
return registered_schemas
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
REGISTERED_SCHEMAS = register_all_tools()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
if __name__ == "__main__":
|
|
175
|
+
if "--check" in sys.argv:
|
|
176
|
+
from rich.console import Console
|
|
177
|
+
from rich.table import Table
|
|
178
|
+
|
|
179
|
+
console = Console(stderr=True, legacy_windows=False)
|
|
180
|
+
table = Table(
|
|
181
|
+
title=f"🌐 Master MCP Sunucusu — Yüklü Araçlar ({len(REGISTERED_SCHEMAS)} Adet)",
|
|
182
|
+
show_header=True,
|
|
183
|
+
header_style="bold magenta",
|
|
184
|
+
show_lines=True,
|
|
185
|
+
)
|
|
186
|
+
table.add_column("Servis", style="bold cyan")
|
|
187
|
+
table.add_column("MCP Tool Adı", style="bold yellow")
|
|
188
|
+
table.add_column("Hedef Endpoint", style="white")
|
|
189
|
+
for s in REGISTERED_SCHEMAS:
|
|
190
|
+
table.add_row(s.service_name, s.function_name, f"{s.method} {s.endpoint_url}")
|
|
191
|
+
console.print(table)
|
|
192
|
+
else:
|
|
193
|
+
mcp.run()
|
ownapi/__init__.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""OwnAPI — Enterprise User-Delegated Browser Middleware & Auto-Validated API SDK."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import pathlib
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from core.api_keys import (
|
|
8
|
+
APIKeyManager,
|
|
9
|
+
InsufficientCreditsError,
|
|
10
|
+
consume_credit,
|
|
11
|
+
generate_api_key,
|
|
12
|
+
get_or_create_tenant,
|
|
13
|
+
get_tenant_info,
|
|
14
|
+
upgrade_plan,
|
|
15
|
+
)
|
|
16
|
+
from core.auto_repair import AutoRepairEngine
|
|
17
|
+
from core.base_client import BaseOwnClient, BaseShadowClient
|
|
18
|
+
from core.consent import USER_DELEGATION_DISCLAIMER, ConsentManager
|
|
19
|
+
from core.hitl_queue import HITLQueueManager
|
|
20
|
+
from core.onboarding import onboard_new_site
|
|
21
|
+
from core.token_store import TokenStore
|
|
22
|
+
from ownapi.sdk import OwnAPI, OwnAPIClient, ServiceNamespaceProxy, ShadowClient
|
|
23
|
+
|
|
24
|
+
__version__ = "1.0.0"
|
|
25
|
+
|
|
26
|
+
_PROJECT_ROOT = pathlib.Path(__file__).resolve().parents[1]
|
|
27
|
+
_REGISTRY_ROOT = _PROJECT_ROOT / "registry"
|
|
28
|
+
|
|
29
|
+
# Doğrudan `from ownapi import thy, trendyol, pegasus` kullanımı için yerel (free/default) vekiller
|
|
30
|
+
thy = ServiceNamespaceProxy("thy", default_tenant_id="default", default_mode="local")
|
|
31
|
+
trendyol = ServiceNamespaceProxy("trendyol", default_tenant_id="default", default_mode="local")
|
|
32
|
+
pegasus = ServiceNamespaceProxy("pegasus", default_tenant_id="default", default_mode="local")
|
|
33
|
+
enuygun = ServiceNamespaceProxy("enuygun", default_tenant_id="default", default_mode="local")
|
|
34
|
+
linkedin_jobs = ServiceNamespaceProxy("linkedin_jobs", default_tenant_id="default", default_mode="local")
|
|
35
|
+
wikipedia = ServiceNamespaceProxy("wikipedia", default_tenant_id="default", default_mode="local")
|
|
36
|
+
hackernews = ServiceNamespaceProxy("hackernews", default_tenant_id="default", default_mode="local")
|
|
37
|
+
github_trending = ServiceNamespaceProxy("github_trending", default_tenant_id="default", default_mode="local")
|
|
38
|
+
coingecko = ServiceNamespaceProxy("coingecko", default_tenant_id="default", default_mode="local")
|
|
39
|
+
yahoo_finance = ServiceNamespaceProxy("yahoo_finance", default_tenant_id="default", default_mode="local")
|
|
40
|
+
edevlet = ServiceNamespaceProxy("edevlet", default_tenant_id="default", default_mode="local")
|
|
41
|
+
hepsiburada = ServiceNamespaceProxy("hepsiburada", default_tenant_id="default", default_mode="local")
|
|
42
|
+
ucak_bileti = ServiceNamespaceProxy("ucak_bileti", default_tenant_id="default", default_mode="local")
|
|
43
|
+
|
|
44
|
+
_DYNAMIC_PROXIES: dict[str, ServiceNamespaceProxy] = {}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def __getattr__(name: str) -> Any:
|
|
48
|
+
"""Yeni eklenen `registry/<site>` servislerinin de `from ownapi import <site>` ile içe aktarılmasını sağlar."""
|
|
49
|
+
if name.startswith("_"):
|
|
50
|
+
raise AttributeError(name)
|
|
51
|
+
clean = name.strip().lower()
|
|
52
|
+
if clean in _DYNAMIC_PROXIES:
|
|
53
|
+
return _DYNAMIC_PROXIES[clean]
|
|
54
|
+
if (_REGISTRY_ROOT / clean / "client.py").exists():
|
|
55
|
+
proxy = ServiceNamespaceProxy(clean, default_tenant_id="default", default_mode="local")
|
|
56
|
+
_DYNAMIC_PROXIES[clean] = proxy
|
|
57
|
+
return proxy
|
|
58
|
+
raise AttributeError(f"module 'ownapi' has no attribute '{name}'")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
__all__ = [
|
|
62
|
+
"OwnAPI",
|
|
63
|
+
"OwnAPIClient",
|
|
64
|
+
"ShadowClient",
|
|
65
|
+
"ServiceNamespaceProxy",
|
|
66
|
+
"BaseOwnClient",
|
|
67
|
+
"BaseShadowClient",
|
|
68
|
+
"APIKeyManager",
|
|
69
|
+
"InsufficientCreditsError",
|
|
70
|
+
"get_or_create_tenant",
|
|
71
|
+
"generate_api_key",
|
|
72
|
+
"consume_credit",
|
|
73
|
+
"upgrade_plan",
|
|
74
|
+
"get_tenant_info",
|
|
75
|
+
"AutoRepairEngine",
|
|
76
|
+
"HITLQueueManager",
|
|
77
|
+
"TokenStore",
|
|
78
|
+
"ConsentManager",
|
|
79
|
+
"USER_DELEGATION_DISCLAIMER",
|
|
80
|
+
"onboard_new_site",
|
|
81
|
+
"thy",
|
|
82
|
+
"trendyol",
|
|
83
|
+
"pegasus",
|
|
84
|
+
"enuygun",
|
|
85
|
+
"linkedin_jobs",
|
|
86
|
+
"wikipedia",
|
|
87
|
+
"hackernews",
|
|
88
|
+
"github_trending",
|
|
89
|
+
"coingecko",
|
|
90
|
+
"yahoo_finance",
|
|
91
|
+
"edevlet",
|
|
92
|
+
"hepsiburada",
|
|
93
|
+
"ucak_bileti",
|
|
94
|
+
]
|
ownapi/cli.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
from rich.console import Console
|
|
11
|
+
from rich.panel import Panel
|
|
12
|
+
from rich.table import Table
|
|
13
|
+
|
|
14
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
15
|
+
try:
|
|
16
|
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
17
|
+
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
|
18
|
+
except Exception:
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
|
22
|
+
if str(PROJECT_ROOT) not in sys.path:
|
|
23
|
+
sys.path.insert(0, str(PROJECT_ROOT))
|
|
24
|
+
|
|
25
|
+
from cli import app as _root_app
|
|
26
|
+
from core.api_keys import get_or_create_tenant, get_tenant_info, upgrade_plan
|
|
27
|
+
|
|
28
|
+
console = Console(legacy_windows=False)
|
|
29
|
+
app = _root_app
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def get_claude_desktop_config_path(custom_path: Path | str | None = None) -> Path:
|
|
33
|
+
"""
|
|
34
|
+
İşletim sistemine göre kullanıcının Claude Desktop (`claude_desktop_config.json`)
|
|
35
|
+
dosya yolunu otomatik olarak tespit eder.
|
|
36
|
+
"""
|
|
37
|
+
if custom_path:
|
|
38
|
+
return Path(custom_path).expanduser().resolve()
|
|
39
|
+
|
|
40
|
+
env_override = os.getenv("OWNAPI_CLAUDE_CONFIG_PATH", "").strip()
|
|
41
|
+
if env_override:
|
|
42
|
+
return Path(env_override).expanduser().resolve()
|
|
43
|
+
|
|
44
|
+
if sys.platform.startswith("win"):
|
|
45
|
+
appdata = os.getenv("APPDATA")
|
|
46
|
+
if appdata:
|
|
47
|
+
return Path(appdata) / "Claude" / "claude_desktop_config.json"
|
|
48
|
+
return Path.home() / "AppData" / "Roaming" / "Claude" / "claude_desktop_config.json"
|
|
49
|
+
if sys.platform == "darwin":
|
|
50
|
+
return (
|
|
51
|
+
Path.home()
|
|
52
|
+
/ "Library"
|
|
53
|
+
/ "Application Support"
|
|
54
|
+
/ "Claude"
|
|
55
|
+
/ "claude_desktop_config.json"
|
|
56
|
+
)
|
|
57
|
+
xdg_config = os.getenv("XDG_CONFIG_HOME")
|
|
58
|
+
if xdg_config:
|
|
59
|
+
return Path(xdg_config) / "Claude" / "claude_desktop_config.json"
|
|
60
|
+
return Path.home() / ".config" / "Claude" / "claude_desktop_config.json"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def configure_claude_desktop_mcp(
|
|
64
|
+
config_path: Path | str | None = None,
|
|
65
|
+
server_name: str = "ownapi",
|
|
66
|
+
tenant_id: str = "default",
|
|
67
|
+
) -> dict[str, Any]:
|
|
68
|
+
"""
|
|
69
|
+
Claude Desktop (`claude_desktop_config.json`) dosyasını bulur (yoksa oluşturur)
|
|
70
|
+
ve mevcut Python yorumlayıcısı ile `master_mcp.py` tam yolunu tek komutla bağlar.
|
|
71
|
+
"""
|
|
72
|
+
target_config = get_claude_desktop_config_path(config_path)
|
|
73
|
+
target_config.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
|
|
75
|
+
existing_data: dict[str, Any] = {}
|
|
76
|
+
if target_config.exists():
|
|
77
|
+
try:
|
|
78
|
+
loaded = json.loads(target_config.read_text(encoding="utf-8"))
|
|
79
|
+
if isinstance(loaded, dict):
|
|
80
|
+
existing_data = loaded
|
|
81
|
+
except Exception:
|
|
82
|
+
existing_data = {}
|
|
83
|
+
|
|
84
|
+
mcp_servers = existing_data.get("mcpServers")
|
|
85
|
+
if not isinstance(mcp_servers, dict):
|
|
86
|
+
mcp_servers = {}
|
|
87
|
+
existing_data["mcpServers"] = mcp_servers
|
|
88
|
+
|
|
89
|
+
python_exe = str(Path(sys.executable).resolve())
|
|
90
|
+
master_mcp_path = str((PROJECT_ROOT / "master_mcp.py").resolve())
|
|
91
|
+
|
|
92
|
+
tenant_record = get_or_create_tenant(tenant_id=tenant_id)
|
|
93
|
+
mcp_entry = {
|
|
94
|
+
"command": python_exe,
|
|
95
|
+
"args": [master_mcp_path],
|
|
96
|
+
"env": {
|
|
97
|
+
"PYTHONIOENCODING": "utf-8",
|
|
98
|
+
"OWNAPI_TENANT_ID": tenant_record["tenant_id"],
|
|
99
|
+
"OWNAPI_API_KEY": tenant_record["api_key"],
|
|
100
|
+
"OWNAPI_BROWSER_MODE": tenant_record["mode"],
|
|
101
|
+
},
|
|
102
|
+
}
|
|
103
|
+
mcp_servers[server_name] = mcp_entry
|
|
104
|
+
|
|
105
|
+
target_config.write_text(
|
|
106
|
+
json.dumps(existing_data, ensure_ascii=False, indent=2) + "\n",
|
|
107
|
+
encoding="utf-8",
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
"config_path": str(target_config),
|
|
112
|
+
"server_name": server_name,
|
|
113
|
+
"python_executable": python_exe,
|
|
114
|
+
"master_mcp_path": master_mcp_path,
|
|
115
|
+
"tenant": tenant_record,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def format_tr_number(value: int) -> str:
|
|
120
|
+
"""Sayıları binlik nokta ayracıyla biçimlendirir (örn. 1000 -> '1.000')."""
|
|
121
|
+
return f"{int(value):,}".replace(",", ".")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@app.command("init")
|
|
125
|
+
def init_command(
|
|
126
|
+
tenant_id: str = typer.Option(
|
|
127
|
+
"default",
|
|
128
|
+
"--tenant",
|
|
129
|
+
"-t",
|
|
130
|
+
help="Başlatılacak ve Claude Desktop'a bağlanacak kiracı ID'si (varsayılan: default)",
|
|
131
|
+
),
|
|
132
|
+
server_name: str = typer.Option(
|
|
133
|
+
"ownapi",
|
|
134
|
+
"--name",
|
|
135
|
+
"-n",
|
|
136
|
+
help="claude_desktop_config.json içindeki MCP sunucu anahtar adı",
|
|
137
|
+
),
|
|
138
|
+
config_path: Path | None = typer.Option(
|
|
139
|
+
None,
|
|
140
|
+
"--config",
|
|
141
|
+
"-c",
|
|
142
|
+
help="Özel claude_desktop_config.json dosya yolu (verilmezse otomatik bulunur)",
|
|
143
|
+
),
|
|
144
|
+
) -> None:
|
|
145
|
+
"""
|
|
146
|
+
Tek komutla Claude Desktop (`claude_desktop_config.json`) dosyasını otomatik bulup
|
|
147
|
+
mevcut Python yorumlayıcısını ve `master_mcp.py` yolunu bağlar.
|
|
148
|
+
"""
|
|
149
|
+
result = configure_claude_desktop_mcp(
|
|
150
|
+
config_path=config_path,
|
|
151
|
+
server_name=server_name,
|
|
152
|
+
tenant_id=tenant_id,
|
|
153
|
+
)
|
|
154
|
+
tenant = result["tenant"]
|
|
155
|
+
credits_str = format_tr_number(tenant.get("credits", 1000))
|
|
156
|
+
|
|
157
|
+
out_console = Console(file=sys.stdout, legacy_windows=False)
|
|
158
|
+
out_console.print(
|
|
159
|
+
Panel.fit(
|
|
160
|
+
f"[bold green]✔ OwnAPI Claude Desktop MCP Entegrasyonu Tamamlandı![/bold green]\n\n"
|
|
161
|
+
f"[bold cyan]📂 Claude Config Dosyası:[/bold cyan] [underline]{result['config_path']}[/underline]\n"
|
|
162
|
+
f"[bold cyan]🐍 Python Yorumlayıcısı:[/bold cyan] [white]{result['python_executable']}[/white]\n"
|
|
163
|
+
f"[bold cyan]🔌 Master MCP Sunucusu:[/bold cyan] [white]{result['master_mcp_path']}[/white]\n"
|
|
164
|
+
f"[bold cyan]🔑 API Anahtarı:[/bold cyan] [bold yellow]{tenant['api_key']}[/bold yellow]\n"
|
|
165
|
+
f"[bold cyan]📦 Aktif Paket / Mod:[/bold cyan] [magenta]{tenant['plan']}[/magenta] ([green]mode=\"{tenant['mode']}\"[/green])\n"
|
|
166
|
+
f"[bold cyan]💳 Kalan Kredi:[/bold cyan] [bold green]{credits_str} kredi[/bold green]",
|
|
167
|
+
title="🚀 OwnAPI Init — Tek Komutla Kurulum",
|
|
168
|
+
border_style="green",
|
|
169
|
+
)
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@app.command("status")
|
|
174
|
+
def status_command(
|
|
175
|
+
tenant_id_or_key: str = typer.Option(
|
|
176
|
+
"default",
|
|
177
|
+
"--tenant",
|
|
178
|
+
"-t",
|
|
179
|
+
help="Durumu görüntülenecek kiracı ID'si veya sk-ownapi-... anahtarı",
|
|
180
|
+
),
|
|
181
|
+
upgrade: str | None = typer.Option(
|
|
182
|
+
None,
|
|
183
|
+
"--upgrade",
|
|
184
|
+
"-u",
|
|
185
|
+
help="İsteğe bağlı paket yükseltme ('starter_cloud' veya 'growth_cloud')",
|
|
186
|
+
),
|
|
187
|
+
) -> None:
|
|
188
|
+
"""
|
|
189
|
+
Kullanıcının kalan kredisini (`1.000` kredi), paketini (`free` / `starter_cloud` / `growth_cloud`),
|
|
190
|
+
çalışma modunu (`local` / `cloud`) ve `sk-ownapi-...` anahtarını terminalde şık bir kutu içinde gösterir.
|
|
191
|
+
"""
|
|
192
|
+
if upgrade:
|
|
193
|
+
info = get_tenant_info(tenant_id_or_key)
|
|
194
|
+
upgrade_plan(info["tenant_id"], plan=upgrade)
|
|
195
|
+
tenant_record = get_tenant_info(info["tenant_id"])
|
|
196
|
+
else:
|
|
197
|
+
tenant_record = get_tenant_info(tenant_id_or_key)
|
|
198
|
+
|
|
199
|
+
credits_fmt = format_tr_number(tenant_record.get("credits", 0))
|
|
200
|
+
consumed_fmt = format_tr_number(tenant_record.get("total_consumed", 0))
|
|
201
|
+
plan_name = str(tenant_record.get("plan", "free"))
|
|
202
|
+
plan_label = str(tenant_record.get("plan_label", plan_name))
|
|
203
|
+
mode_name = str(tenant_record.get("mode", "local"))
|
|
204
|
+
api_key = str(tenant_record.get("api_key", ""))
|
|
205
|
+
price_usd = int(tenant_record.get("price_usd", 0))
|
|
206
|
+
|
|
207
|
+
table = Table(show_header=False, box=None, pad_edge=False)
|
|
208
|
+
table.add_column("Alan", style="bold cyan", width=22)
|
|
209
|
+
table.add_column("Değer", style="white")
|
|
210
|
+
|
|
211
|
+
table.add_row("👤 Kiracı (Tenant)", f"[bold white]{tenant_record.get('tenant_id', 'default')}[/bold white]")
|
|
212
|
+
table.add_row("📦 Aktif Paket", f"[bold magenta]{plan_name}[/bold magenta] — {plan_label} ([yellow]${price_usd}[/yellow])")
|
|
213
|
+
table.add_row("⚙️ Çalışma Modu", f"[bold green]{mode_name}[/bold green]")
|
|
214
|
+
table.add_row("💳 Kalan Kredi", f"[bold green]{credits_fmt} kredi[/bold green]")
|
|
215
|
+
table.add_row("📊 Harcanan Kredi", f"[dim]{consumed_fmt} kredi[/dim]")
|
|
216
|
+
table.add_row("🔑 API Anahtarı", f"[bold yellow]{api_key}[/bold yellow]")
|
|
217
|
+
|
|
218
|
+
out_console = Console(file=sys.stdout, legacy_windows=False)
|
|
219
|
+
out_console.print(
|
|
220
|
+
Panel.fit(
|
|
221
|
+
table,
|
|
222
|
+
title="💎 OwnAPI Hesap & Kredi Durumu (ownapi status)",
|
|
223
|
+
border_style="cyan",
|
|
224
|
+
)
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@app.command("start")
|
|
229
|
+
def start_command(
|
|
230
|
+
host: str = typer.Option("127.0.0.1", "--host", "-h", help="Yerel sunucu dinleme adresi"),
|
|
231
|
+
port: int = typer.Option(8000, "--port", "-p", help="Yerel sunucu port numarası (varsayılan: 8000)"),
|
|
232
|
+
tenant_id: str = typer.Option("default", "--tenant", "-t", help="Aktif kiracı ID'si"),
|
|
233
|
+
open_browser: bool = typer.Option(
|
|
234
|
+
True,
|
|
235
|
+
"--open-browser/--no-open-browser",
|
|
236
|
+
help="Sunucu başladığında Web Dashboard'u varsayılan tarayıcıda otomatik aç",
|
|
237
|
+
),
|
|
238
|
+
init_mcp: bool = typer.Option(
|
|
239
|
+
True,
|
|
240
|
+
"--init-mcp/--no-init-mcp",
|
|
241
|
+
help="Başlangıçta Claude Desktop MCP bağlantısını otomatik doğrula/güncelle",
|
|
242
|
+
),
|
|
243
|
+
reload: bool = typer.Option(False, "--reload", help="Geliştirici otomatik yenileme modu"),
|
|
244
|
+
check_only: bool = typer.Option(
|
|
245
|
+
False,
|
|
246
|
+
"--check",
|
|
247
|
+
help="Sunucuyu bloklamadan yapılandırmayı ve masaüstü köprüsünü doğrulayıp çık (test amaçlı)",
|
|
248
|
+
),
|
|
249
|
+
) -> None:
|
|
250
|
+
"""
|
|
251
|
+
Tek komutla OwnAPI Yerel Sunucusunu (Web Dashboard & REST API), Tarayıcı Köprüsünü
|
|
252
|
+
ve Claude Desktop MCP bağlantısını başlatır (`ownapi start`).
|
|
253
|
+
"""
|
|
254
|
+
import threading
|
|
255
|
+
import webbrowser
|
|
256
|
+
|
|
257
|
+
from server import run_server
|
|
258
|
+
|
|
259
|
+
tenant_record = get_or_create_tenant(tenant_id=tenant_id)
|
|
260
|
+
mcp_status_line = "[dim]Atlandı (--no-init-mcp)[/dim]"
|
|
261
|
+
if init_mcp:
|
|
262
|
+
try:
|
|
263
|
+
mcp_res = configure_claude_desktop_mcp(tenant_id=tenant_id)
|
|
264
|
+
mcp_status_line = f"[bold green]✔ Bağlı[/bold green] ([dim]{mcp_res['config_path']}[/dim])"
|
|
265
|
+
except Exception as exc:
|
|
266
|
+
mcp_status_line = f"[yellow]⚠ Uyarı ({exc})[/yellow]"
|
|
267
|
+
|
|
268
|
+
dashboard_url = f"http://{host}:{port}"
|
|
269
|
+
credits_fmt = format_tr_number(tenant_record.get("credits", 1000))
|
|
270
|
+
|
|
271
|
+
out_console = Console(file=sys.stdout, legacy_windows=False)
|
|
272
|
+
out_console.print(
|
|
273
|
+
Panel.fit(
|
|
274
|
+
f"[bold green]🟢 Bağlı — Bilgisayarın ve Tarayıcı Köprün Hazır![/bold green]\n\n"
|
|
275
|
+
f"[bold cyan]🌐 Web Dashboard & SaaS Panel:[/bold cyan] [bold underline white]{dashboard_url}[/bold underline white]\n"
|
|
276
|
+
f"[bold cyan]📚 OpenAPI / Swagger Docs:[/bold cyan] [underline]{dashboard_url}/docs[/underline]\n"
|
|
277
|
+
f"[bold cyan]👤 Aktif Kiracı / Paket:[/bold cyan] [bold white]{tenant_record['tenant_id']}[/bold white] / [magenta]{tenant_record['plan']}[/magenta] ([green]mode=\"{tenant_record['mode']}\"[/green])\n"
|
|
278
|
+
f"[bold cyan]💳 Kalan Kredi:[/bold cyan] [bold green]{credits_fmt} kredi[/bold green]\n"
|
|
279
|
+
f"[bold cyan]🔑 API Anahtarı:[/bold cyan] [bold yellow]{tenant_record['api_key']}[/bold yellow]\n"
|
|
280
|
+
f"[bold cyan]🔌 Claude Desktop MCP:[/bold cyan] {mcp_status_line}",
|
|
281
|
+
title="🚀 OwnAPI Desktop Bridge & Local Server (ownapi start)",
|
|
282
|
+
border_style="green",
|
|
283
|
+
)
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
if check_only:
|
|
287
|
+
return
|
|
288
|
+
|
|
289
|
+
if open_browser and not os.getenv("OWNAPI_DISABLE_AUTO_BROWSER"):
|
|
290
|
+
def _launch_browser() -> None:
|
|
291
|
+
try:
|
|
292
|
+
webbrowser.open(dashboard_url)
|
|
293
|
+
except Exception:
|
|
294
|
+
pass
|
|
295
|
+
|
|
296
|
+
timer = threading.Timer(1.2, _launch_browser)
|
|
297
|
+
timer.daemon = True
|
|
298
|
+
timer.start()
|
|
299
|
+
|
|
300
|
+
run_server(host=host, port=port, reload=reload)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def main() -> None:
|
|
304
|
+
"""`ownapi` ve `own-api` terminal komutlarının ana giriş noktası."""
|
|
305
|
+
app()
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
if __name__ == "__main__":
|
|
309
|
+
main()
|