Repository navigation
Expand file tree
/
Copy pathtelegram_dev_install.py
More file actions
238 lines (215 loc) · 11.3 KB
/
Copy pathtelegram_dev_install.py
File metadata and controls
238 lines (215 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""Install MCP + skill into one chosen project, preserving existing settings.
Runs from a source checkout (``uv run telegram-dev install``) or from the
published package (``uvx telegram-dev install``). A checkout install
points the agent at the checkout's Python; a package install points it at a
pinned ``uvx`` launcher, so nothing has to stay on disk besides the uv cache.
"""
import argparse
from collections.abc import Mapping
from datetime import datetime, timezone
import hashlib
import importlib.metadata
import importlib.util
import json
import os
from pathlib import Path
import shutil
import sys
from urllib.parse import unquote, urlsplit
import tomlkit
ROOT = Path(__file__).resolve().parent
DISTRIBUTION = 'telegram-dev'
MARKER = '.telegram-dev-install.json'
LAYOUT = {
'codex': ('.codex/config.toml', '.agents/skills/telegram-dev'),
'claude': ('.mcp.json', '.claude/skills/telegram-dev'),
'cursor': ('.cursor/mcp.json', '.cursor/skills/telegram-dev'),
}
def file_hashes(directory):
hashes = {}
for path in sorted(directory.rglob('*')):
if path.is_symlink():
raise ValueError(f'Skill contains a symbolic link; review it before updating: {path}')
if path.is_file() and path.relative_to(directory).as_posix() != MARKER:
hashes[path.relative_to(directory).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
return hashes
def read_ownership(skill, agent, config_name):
marker = skill / MARKER
if not marker.is_file() or marker.is_symlink():
raise ValueError('Existing skill has no Telegram Dev ownership manifest. For a legacy install, '
'back up and remove its skill directory and telegram-knowledge MCP entry, then install again.')
try:
metadata = json.loads(marker.read_text(encoding='utf-8'))
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
raise ValueError('The Telegram Dev ownership manifest is invalid; review the installation manually') from exc
if (not isinstance(metadata, dict) or metadata.get('schema_version') != 1
or metadata.get('agent') != agent or metadata.get('config') != config_name
or not isinstance(metadata.get('files'), dict) or not isinstance(metadata.get('connection'), dict)
or not isinstance(metadata.get('source_root'), str)):
raise ValueError('The Telegram Dev ownership manifest does not match this installation')
if file_hashes(skill) != metadata['files']:
raise ValueError('Installed Telegram Dev skill has local changes, added files or removed files. '
'Back up and resolve those changes before --update; no files were overwritten.')
return metadata
def is_checkout(root=None):
root = root or ROOT
return (root / 'skills/telegram-dev/SKILL.md').is_file() and (root / 'pyproject.toml').is_file()
def skill_source():
if is_checkout():
return ROOT / 'skills/telegram-dev'
spec = importlib.util.find_spec('telegram_dev_skill')
locations = list(spec.submodule_search_locations or []) if spec else []
for location in locations:
if Path(location, 'SKILL.md').is_file():
return Path(location)
raise ValueError('The installed package has no bundled Telegram Dev skill; reinstall telegram-dev')
def package_version():
if is_checkout():
return str(tomlkit.parse((ROOT / 'pyproject.toml').read_text(encoding='utf-8'))['project']['version'])
return importlib.metadata.version(DISTRIBUTION)
def package_spec(version):
"""Return the uvx --from requirement that reproduces the running package."""
try:
direct = importlib.metadata.distribution(DISTRIBUTION).read_text('direct_url.json')
except importlib.metadata.PackageNotFoundError:
direct = None
if direct:
info = json.loads(direct)
url = info.get('url', '')
if urlsplit(url).password or (urlsplit(url).username and not url.startswith('file:')):
raise ValueError('The package was installed from a URL with credentials; pass a public --from requirement instead')
if info.get('subdirectory'):
url = f"{url}#subdirectory={info['subdirectory']}"
vcs = info.get('vcs_info')
if vcs and vcs.get('vcs') == 'git':
# Pin the exact commit: a branch name would let the server drift from the copied skill.
revision = vcs.get('commit_id') or vcs.get('requested_revision')
return f'git+{url}@{revision}' if revision else f'git+{url}'
if url.startswith('file://'):
path = unquote(urlsplit(url).path)
if os.name == 'nt' and path.startswith('/'):
path = path[1:]
return str(Path(path))
return url
return f'{DISTRIBUTION}=={version}'
def server_connection(version, source=None):
if source is None and is_checkout():
return {'command': sys.executable, 'args': [str(ROOT / 'telegram_knowledge.py'), 'serve']}
return {'command': 'uvx', 'args': ['--from', source or package_spec(version), 'telegram-dev', 'serve']}
def install(agent, project, update=False, source=None):
project = Path(project).resolve()
if project == Path.home().resolve():
raise ValueError('Refusing to install into the home directory, where agents read user-wide settings; '
'run inside a project or pass --project explicitly')
if not project.is_dir():
raise ValueError('Project directory must already exist')
if agent not in LAYOUT:
raise ValueError('Unknown agent')
config_name, skill_name = LAYOUT[agent]
config = project / config_name
skill = project / skill_name
if skill.is_symlink() or config.is_symlink():
raise ValueError('Skill/config uses a symbolic link; review this installation manually')
if update:
if not skill.is_dir():
raise ValueError('No existing Telegram Dev skill to update; install without --update first')
ownership = read_ownership(skill, agent, config_name)
else:
ownership = None
stamp = datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S%f')
version = package_version()
command = server_connection(version, source)
connection = command if agent == 'codex' else {'type': 'stdio', **command}
# Parse before writing anything: malformed config is reported, never replaced.
if agent == 'codex':
data = tomlkit.parse(config.read_text(encoding='utf-8')) if config.exists() else tomlkit.document()
if 'mcp_servers' not in data:
data['mcp_servers'] = tomlkit.table()
servers = data['mcp_servers']
else:
data = json.loads(config.read_text(encoding='utf-8')) if config.exists() else {}
if not isinstance(data, dict):
raise ValueError('Agent config must be a JSON object')
servers = data.setdefault('mcpServers', {})
if not isinstance(servers, Mapping):
raise ValueError('MCP server configuration must be a table/object')
existing = servers.get('telegram-knowledge')
if update:
if (not isinstance(existing, Mapping)
or any(existing.get(key) != value for key, value in ownership['connection'].items())
or any(key not in ownership['connection'] for key in connection)):
raise ValueError('telegram-knowledge MCP connection no longer matches the managed installation. '
'Review the connection manually; --update will not overwrite it.')
# Preserve user settings such as env and timeouts attached to this connection.
for key, value in connection.items():
existing[key] = value
else:
if 'telegram-knowledge' in servers:
raise ValueError('telegram-knowledge is already configured; inspect/update its existing entry instead of overwriting it')
if skill.exists():
raise ValueError(f'Skill already exists: {skill}; inspect it before replacing')
servers['telegram-knowledge'] = connection
content = tomlkit.dumps(data) if agent == 'codex' else json.dumps(data, indent=2) + '\n'
skill_dir = skill_source()
if not (skill_dir / 'SKILL.md').is_file():
raise ValueError('The source checkout has no Telegram Dev SKILL.md')
source_files = file_hashes(skill_dir)
config.parent.mkdir(parents=True, exist_ok=True)
skill.parent.mkdir(parents=True, exist_ok=True)
stage = skill.with_name('.telegram-dev-stage-' + stamp)
# Keep backups outside agent discovery directories so they cannot load as duplicate skills.
skill_backup = project / '.telegram-dev-backups' / (agent + '-' + stamp) / 'skill' if update else None
config_backup = config.with_name(config.name + '.backup-' + stamp) if config.exists() else None
pending = config.with_name(config.name + '.telegram-dev-' + stamp)
promoted = old_moved = False
try:
shutil.copytree(skill_dir, stage, ignore=shutil.ignore_patterns('__pycache__'))
if file_hashes(stage) != source_files:
raise ValueError('Source skill changed during installation; retry after the source checkout is stable')
metadata = {
'schema_version': 1, 'version': str(version), 'source_root': str(skill_dir if not is_checkout() else ROOT),
'agent': agent, 'config': config_name, 'connection': connection,
'files': source_files,
}
(stage / MARKER).write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8')
pending.write_text(content, encoding='utf-8')
if config_backup:
shutil.copy2(config, config_backup)
if update:
skill_backup.parent.mkdir(parents=True, exist_ok=True)
skill.replace(skill_backup)
old_moved = True
stage.replace(skill)
promoted = True
pending.replace(config)
except Exception:
if promoted:
shutil.rmtree(skill)
if old_moved:
skill_backup.replace(skill)
if skill_backup and skill_backup.parent.exists() and not any(skill_backup.parent.iterdir()):
skill_backup.parent.rmdir()
if stage.exists():
shutil.rmtree(stage)
pending.unlink(missing_ok=True)
raise
return {
'config': str(config), 'skill': str(skill), 'version': str(version), 'updated': update,
'backups': [str(path) for path in (config_backup, skill_backup) if path],
'restart': 'Open a new agent session and enable/trust the project MCP connection if prompted.',
}
def main(argv=None, prog=None):
parser = argparse.ArgumentParser(prog=prog, description='Connect the Telegram Dev MCP server and skill to one project.')
parser.add_argument('--agent', required=True, choices=sorted(LAYOUT), help='Agent that will use the project')
parser.add_argument('--project', default='.', help='Existing project directory (default: current directory)')
parser.add_argument('--update', action='store_true', help='Update an unchanged installation created by this installer')
parser.add_argument('--from', dest='source', metavar='SPEC',
help='uvx --from requirement for the MCP server (default: the running package)')
args = parser.parse_args(argv)
try:
result = install(args.agent, args.project, update=args.update, source=args.source)
except ValueError as exc:
parser.error(str(exc))
print(json.dumps(result, indent=2))
if __name__ == '__main__':
main()