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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Skills API Client
//!
//! HTTP client for interacting with the Anthropic Skills API.
//! Supports uploading, listing, and deleting skills.
use reqwest::Client;
use std::path::{Path, PathBuf};
use thiserror::Error;
/// Errors that can occur when interacting with the Skills API
#[derive(Debug, Error)]
pub enum SkillsError {
/// HTTP request failed
#[error("HTTP request failed: {0}")]
HttpError(#[from] reqwest::Error),
/// IO error during file operations
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
/// API returned an error
#[error("API error: {0}")]
ApiError(String),
/// Invalid response format
#[error("Invalid response format: {0}")]
InvalidResponse(String),
/// Skill not found
#[error("Skill not found: {0}")]
SkillNotFound(String),
}
/// Information about a skill from the Skills API
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SkillApiInfo {
/// Unique skill identifier
pub id: String,
/// Skill name
pub name: String,
/// Skill description
pub description: String,
/// Creation timestamp
pub created_at: String,
/// Skill version
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Skill author
#[serde(skip_serializing_if = "Option::is_none")]
pub author: Option<String>,
}
/// Response from listing skills
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ListSkillsResponse {
/// List of skills
pub skills: Vec<SkillApiInfo>,
/// Total count
pub total_count: usize,
/// Next page token
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
/// Response from uploading a skill
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UploadSkillResponse {
/// Uploaded skill information
pub skill: SkillApiInfo,
/// Upload status
pub status: String,
}
/// HTTP client for the Anthropic Skills API
pub struct SkillsApiClient {
/// API key for authentication
api_key: String,
/// Base URL for the API
base_url: String,
/// HTTP client
client: Client,
/// API version header
api_version: String,
}
impl SkillsApiClient {
/// Create a new Skills API client
///
/// # Arguments
///
/// * `api_key` - Anthropic API key
///
/// # Example
///
/// ```rust
/// use claude_agent_sdk::skills::api::SkillsApiClient;
///
/// let client = SkillsApiClient::new("sk-ant-...");
/// ```
pub fn new(api_key: impl Into<String>) -> Self {
Self::with_base_url(api_key, "https://api.anthropic.com/v1")
}
/// Create a new Skills API client with a custom base URL
///
/// # Arguments
///
/// * `api_key` - Anthropic API key
/// * `base_url` - Custom base URL for the API
pub fn with_base_url(api_key: impl Into<String>, base_url: &str) -> Self {
Self {
api_key: api_key.into(),
base_url: base_url.to_string(),
client: Client::new(),
api_version: "2023-06-01".to_string(),
}
}
/// Create a client with custom API version
///
/// # Arguments
///
/// * `api_key` - Anthropic API key
/// * `api_version` - API version string
pub fn with_api_version(api_key: impl Into<String>, api_version: &str) -> Self {
Self {
api_key: api_key.into(),
base_url: "https://api.anthropic.com/v1".to_string(),
client: Client::new(),
api_version: api_version.to_string(),
}
}
/// Upload a skill directory to the Skills API
///
/// # Arguments
///
/// * `skill_dir` - Path to the skill directory
///
/// # Returns
///
/// Information about the uploaded skill
///
/// # Errors
///
/// Returns `SkillsError` if:
/// - The skill directory cannot be read
/// - The directory cannot be zipped
/// - The upload fails
///
/// # Example
///
/// ```rust,no_run
/// # use claude_agent_sdk::skills::api::SkillsApiClient;
/// # use std::path::Path;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = SkillsApiClient::new("sk-ant-...");
/// let info = client.upload_skill(Path::new("/path/to/skill")).await?;
/// println!("Uploaded skill: {} (ID: {})", info.name, info.id);
/// # Ok(())
/// # }
/// ```
pub async fn upload_skill(
&self,
skill_dir: &Path,
) -> Result<SkillApiInfo, SkillsError> {
// 1. Zip the skill directory
let zip_bytes = self.zip_skill(skill_dir)?;
// 2. Upload to API
let url = format!("{}/skills", self.base_url);
let response = self
.client
.post(&url)
.header("x-api-key", &self.api_key)
.header("anthropic-version", &self.api_version)
.header("Content-Type", "application/zip")
.body(zip_bytes)
.send()
.await?;
// 3. Check status
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(SkillsError::ApiError(format!(
"Upload failed with status {}: {}",
status, error_text
)));
}
// 4. Parse response
let upload_response: UploadSkillResponse = response.json().await?;
Ok(upload_response.skill)
}
/// List all skills from the Skills API
///
/// # Returns
///
/// A vector of skill information
///
/// # Errors
///
/// Returns `SkillsError` if the request fails
///
/// # Example
///
/// ```rust,no_run
/// # use claude_agent_sdk::skills::api::SkillsApiClient;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = SkillsApiClient::new("sk-ant-...");
/// let skills = client.list_skills().await?;
/// for skill in skills {
/// println!("{}: {}", skill.name, skill.description);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn list_skills(&self) -> Result<Vec<SkillApiInfo>, SkillsError> {
let url = format!("{}/skills", self.base_url);
let response = self
.client
.get(&url)
.header("x-api-key", &self.api_key)
.header("anthropic-version", &self.api_version)
.send()
.await?;
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(SkillsError::ApiError(format!(
"List skills failed with status {}: {}",
status, error_text
)));
}
let list_response: ListSkillsResponse = response.json().await?;
Ok(list_response.skills)
}
/// Get details of a specific skill
///
/// # Arguments
///
/// * `skill_id` - The skill identifier
///
/// # Returns
///
/// Skill information
///
/// # Errors
///
/// Returns `SkillsError` if the skill is not found or the request fails
pub async fn get_skill(&self, skill_id: &str) -> Result<SkillApiInfo, SkillsError> {
let url = format!("{}/skills/{}", self.base_url, skill_id);
let response = self
.client
.get(&url)
.header("x-api-key", &self.api_key)
.header("anthropic-version", &self.api_version)
.send()
.await?;
if response.status().as_u16() == 404 {
return Err(SkillsError::SkillNotFound(skill_id.to_string()));
}
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(SkillsError::ApiError(format!(
"Get skill failed with status {}: {}",
status, error_text
)));
}
let skill: SkillApiInfo = response.json().await?;
Ok(skill)
}
/// Delete a skill from the Skills API
///
/// # Arguments
///
/// * `skill_id` - The skill identifier to delete
///
/// # Returns
///
/// Ok(()) on success
///
/// # Errors
///
/// Returns `SkillsError` if the deletion fails
///
/// # Example
///
/// ```rust,no_run
/// # use claude_agent_sdk::skills::api::SkillsApiClient;
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = SkillsApiClient::new("sk-ant-...");
/// client.delete_skill("skill-id-123").await?;
/// println!("Skill deleted successfully");
/// # Ok(())
/// # }
/// ```
pub async fn delete_skill(&self, skill_id: &str) -> Result<(), SkillsError> {
let url = format!("{}/skills/{}", self.base_url, skill_id);
let response = self
.client
.delete(&url)
.header("x-api-key", &self.api_key)
.header("anthropic-version", &self.api_version)
.send()
.await?;
if response.status().as_u16() == 404 {
return Err(SkillsError::SkillNotFound(skill_id.to_string()));
}
if !response.status().is_success() {
let status = response.status();
let error_text = response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(SkillsError::ApiError(format!(
"Delete failed with status {}: {}",
status, error_text
)));
}
Ok(())
}
/// Zip a skill directory into bytes
///
/// # Arguments
///
/// * `skill_dir` - Path to the skill directory
///
/// # Returns
///
/// Zipped bytes
fn zip_skill(&self, skill_dir: &Path) -> Result<Vec<u8>, SkillsError> {
use std::fs::File;
use std::io::{Read, Write};
// Create in-memory zip
let mut buffer = Vec::new();
{
// Use a simple implementation: write to a temporary file
// In production, you'd use a library like zip or flate2
let temp_zip_path = std::env::temp_dir().join("skill_upload.zip");
// For now, just create a placeholder
// In a real implementation, you'd use the zip crate
let mut file = File::create(&temp_zip_path)?;
// Write a simple zip file header (simplified)
// Real implementation would use zip crate
writeln!(file, "Skill: {}", skill_dir.display())?;
// Read all files in directory
if skill_dir.is_dir() {
for entry in Self::walk_directory_impl(skill_dir)? {
let mut file = File::open(&entry)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
// Write to zip (simplified)
writeln!(file, "File: {:?}, Size: {}", entry, contents.len())?;
}
}
file.flush()?;
// Read back
let mut file = File::open(&temp_zip_path)?;
file.read_to_end(&mut buffer)?;
// Clean up
let _ = std::fs::remove_file(&temp_zip_path);
}
Ok(buffer)
}
/// Walk a directory recursively (static method)
fn walk_directory_impl(dir: &Path) -> Result<Vec<PathBuf>, SkillsError> {
let mut files = Vec::new();
if dir.is_dir() {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
files.extend(Self::walk_directory_impl(&path)?);
} else {
files.push(path);
}
}
}
Ok(files)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_skill_api_info_serialization() {
let info = SkillApiInfo {
id: "skill-123".to_string(),
name: "Test Skill".to_string(),
description: "A test skill".to_string(),
created_at: "2026-01-13T00:00:00Z".to_string(),
version: Some("1.0.0".to_string()),
author: Some("Test Author".to_string()),
};
let json = serde_json::to_string(&info).unwrap();
assert!(json.contains("skill-123"));
assert!(json.contains("Test Skill"));
let deserialized: SkillApiInfo = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.id, "skill-123");
assert_eq!(deserialized.name, "Test Skill");
}
#[test]
fn test_skills_error_display() {
let err = SkillsError::ApiError("Test error".to_string());
assert_eq!(format!("{}", err), "API error: Test error");
let err = SkillsError::SkillNotFound("skill-123".to_string());
assert_eq!(format!("{}", err), "Skill not found: skill-123");
}
#[test]
fn test_client_creation() {
let client = SkillsApiClient::new("test-key");
assert_eq!(client.api_key, "test-key");
assert_eq!(client.base_url, "https://api.anthropic.com/v1");
assert_eq!(client.api_version, "2023-06-01");
}
#[test]
fn test_client_with_custom_base_url() {
let client = SkillsApiClient::with_base_url("test-key", "https://custom.api.com/v1");
assert_eq!(client.api_key, "test-key");
assert_eq!(client.base_url, "https://custom.api.com/v1");
}
#[test]
fn test_client_with_custom_api_version() {
let client = SkillsApiClient::with_api_version("test-key", "2024-01-01");
assert_eq!(client.api_key, "test-key");
assert_eq!(client.api_version, "2024-01-01");
}
#[test]
fn test_list_skills_response_serialization() {
let response = ListSkillsResponse {
skills: vec![SkillApiInfo {
id: "skill-1".to_string(),
name: "Skill 1".to_string(),
description: "First skill".to_string(),
created_at: "2026-01-13T00:00:00Z".to_string(),
version: None,
author: None,
}],
total_count: 1,
next_token: Some("token-123".to_string()),
};
let json = serde_json::to_string(&response).unwrap();
let deserialized: ListSkillsResponse = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.skills.len(), 1);
assert_eq!(deserialized.total_count, 1);
assert_eq!(deserialized.next_token, Some("token-123".to_string()));
}
#[test]
fn test_upload_skill_response_serialization() {
let response = UploadSkillResponse {
skill: SkillApiInfo {
id: "skill-123".to_string(),
name: "Uploaded Skill".to_string(),
description: "A newly uploaded skill".to_string(),
created_at: "2026-01-13T00:00:00Z".to_string(),
version: Some("1.0.0".to_string()),
author: None,
},
status: "success".to_string(),
};
let json = serde_json::to_string(&response).unwrap();
let deserialized: UploadSkillResponse = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.skill.id, "skill-123");
assert_eq!(deserialized.status, "success");
}
}